Pandas:比较系列中的列表对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53102731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: compare list objects in Series
提问by Shiang Hoo
In my dataframe a column is made up of lists, for example:
在我的数据框中,一列由列表组成,例如:
df = pd.DataFrame({'A':[[1,2],[2,4],[3,1]]})
I need to find out the location of list [1,2] in this dataframe. I tried:
我需要在这个数据框中找出列表 [1,2] 的位置。我试过:
df.loc[df['A'] == [1,2]]
and
和
df.loc[df['A'] == [[1,2]]]
but failed totally. The comparison seems very simple but that just doesn't work. Am I missing something here?
但完全失败了。比较看起来很简单,但这行不通。我在这里错过了什么吗?
回答by YOBEN_S
Do not use list
in cell, it creates a lot of problem for pandas
. If you do need an object
column, using tuple
:
不要list
在单元格中使用,它会给pandas
. 如果您确实需要一object
列,请使用tuple
:
df.A.map(tuple).isin([(1,2)])
Out[293]:
0 True
1 False
2 False
Name: A, dtype: bool
#df[df.A.map(tuple).isin([(1,2)])]
回答by Sandeep Kadapa
You can use apply
and compare as:
您可以使用apply
和比较为:
df['A'].apply(lambda x: x==[1,2])
0 True
1 False
2 False
Name: A, dtype: bool
print(df[df['A'].apply(lambda x: x==[1,2])])
A
0 [1, 2]
回答by piRSquared
With Numpy arrays
使用 Numpy 数组
df.assign(B=(np.array(df.A.tolist()) == [1, 2]).all(1))
A B
0 [1, 2] True
1 [2, 4] False
2 [3, 1] False
回答by Vaishali
Using numpy
使用 numpy
df.A.apply(lambda x: (np.array(x) == np.array([1,2])).all())
0 True
1 False
2 False
回答by U10-Forward
Or:
或者:
df['A'].apply(([1,2]).__eq__)
Then:
然后:
df[df['A'].apply(([1,2]).__eq__)]