![](/img/trans.png)
[英]Python, Pandas: How to check if a row contains values found in another row?
[英]How to check if a Pandas row contains an empty set
我想檢查Pandas Dataframe行是否在特定列中包含空集,即
d = {'col1': [1, 2], 'col2': [3, {}]}
df2 = pd.DataFrame(data=d)
col1 col2
0 1 3
1 2 {}
接着
df2['col_2_contains_empty_set'] = ? # how to implement this
應該給
col1 col2 col_2_contains_empty_set
0 1 3 False
1 2 {} True
這樣做的正確方法是什么? 做不到
bool(df['col2'])
要么
df['col2'].bool()
我認為,由於Series
具有模糊的布爾值。
單程:
df2.apply(lambda x: any(x.values == {}), axis=1)
輸出:
0 False
1 True
dtype: bool
要么
df2['c'] = np.max(df2.values == {}, 1).astype(bool)
輸出:
col1 col2 c
0 1 3 False
1 2 {} True
您只需將df2.values
與空字典進行比較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
您可以利用len({})= 0並應用lambda函數的事實:
df2['col2'].apply(lambda x: len(x)==0)
請注意,對於空列表和dicts,這將返回True。
df2.applymap(type)==type({})
Out[1044]:
col1 col2
0 False False
1 False True
在追回它之后
df2['C']=(df2.applymap(type)==type({})).any(1)
df2
Out[1052]:
col1 col2 C
0 1 3 False
1 2 {} True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.