如何检查 Pandas 行是否包含空集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47762728/
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
How to check if a Pandas row contains an empty set
提问by Zubo
I want to check if a Pandas Dataframe row contains an empty set in a specific column, i.e.
我想检查 Pandas Dataframe 行是否在特定列中包含空集,即
d = {'col1': [1, 2], 'col2': [3, {}]}
df2 = pd.DataFrame(data=d)
col1 col2
0 1 3
1 2 {}
and then
进而
df2['col_2_contains_empty_set'] = ? # how to implement this
should give
应该给
col1 col2 col_2_contains_empty_set
0 1 3 False
1 2 {} True
What's the correct way to do this? Can't do
这样做的正确方法是什么?做不到
bool(df['col2'])
or
或者
df['col2'].bool()
as Series
are have ambiguous Boolean values, I think.
Series
我认为,因为有不明确的布尔值。
回答by Scott Boston
One way:
单程:
df2.apply(lambda x: any(x.values == {}), axis=1)
Output:
输出:
0 False
1 True
dtype: bool
OR
或者
df2['c'] = np.max(df2.values == {}, 1).astype(bool)
Output:
输出:
col1 col2 c
0 1 3 False
1 2 {} True
回答by Sebastian
You can just compare df2.values
to an empty dictionary:
您可以与df2.values
空字典进行比较:
In [ ]: df2['col_2_contains_empty_set'] = (df2.values == {}).any(axis=1)
...: df2
Out[ ]:
col1 col2 col_2_contains_empty_set
0 1 3 False
1 2 {} True
回答by John Santa Maria
You can take advantage of the fact that len({})=0 and apply a lambda function:
您可以利用 len({})=0 并应用 lambda 函数这一事实:
df2['col2'].apply(lambda x: len(x)==0)
Note that this will return True for empty lists and dicts as well.
请注意,这也将为空列表和字典返回 True。
回答by YOBEN_S
df2.applymap(type)==type({})
Out[1044]:
col1 col2
0 False False
1 False True
after assgin it back
重新分配后
df2['C']=(df2.applymap(type)==type({})).any(1)
df2
Out[1052]:
col1 col2 C
0 1 3 False
1 2 {} True