让我们拥有这个数据框
d = {'col1': [[0,1], [0,2], [1,2], [2,3]], 'col2': ["a", "b", "c", "d"]}
df = pandas.DataFrame(data=d)
col1 col2
0 [0, 1] a
1 [0, 2] b
2 [1, 2] c
3 [2, 3] d
现在我需要在 col1 中找到特定列表并返回该行的 col2 中的值
例如,我想查找 [0,2] 并得到“b”作为返回
我已阅读此帖子,了解如何执行此操作:extract column value based on another column pandas dataframe
但是当我尝试在那里应用答案时,我没有得到我需要的结果
df.loc[df['col1'] == [0,2], 'col2']
ValueError: Arrays were different lengths: 4 vs 2
df.query('col1==[0,2]')
SystemError: <built-in method view of numpy.ndarray object at 0x000000000D67FA80> returned a result with an error set
最佳答案
一种可能的解决方案是比较元组
或集合
:
mask = df['col1'].apply(tuple) == tuple([0,2])
mask = df['col1'].apply(set) == set([0,2])
或者如果Series
的每个值的长度相同并且比较list
或array
的长度也相同,则通过数组进行比较:
mask = (np.array(df['col1'].values.tolist())== [0,2]).all(axis=1)
s = df.loc[mask, 'col2']
print (s)
1 b
Name: col2, dtype: object
关于python - 如何在 DataFrame 中找到包含特定列表的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51653110/