在資料框中。列中的每一行都B包含一個串列,該串列以object資料型別存盤。我想將每一行B與另一個串列進行比較。如果它們的值相等,我想添加一個新列指示TRUE,否則,FALSE。
df
B
"1st", "2nd", "3rd"
"2nd", "1st", "4th"
"1st", "2nd", "3rd"
我iterrows()用于回圈成行:
for index, row in df[['B']].iterrows():
set(row['B']) == set(['1st', '2nd', '3rd'])
錯誤顯示TypeError: 'float' object is not iterable,但我在比較中沒有任何數字,為什么會發生?此外,如果 I print(set(row['B']) == set(['1st', '2nd', '3rd'])),它顯示TRUE/ FALSE。這是為什么?
uj5u.com熱心網友回復:
該錯誤表明“B”中有一些 NaN 值。看看
len(df['B']) == len(df['B'].dropna())
是真的。
此外iterrows,您可以使用串列推導來檢查是否有串列:
df = pd.DataFrame({'B':[["1st", "2nd", "3rd"], ["2nd", "1st", "4th"], ["1st", "2nd", "3rd"], np.nan]})
df['new_col'] = [set(x)==set(['1st', '2nd', '3rd']) if isinstance(x, list) else False for x in df['B']]
輸出:
new_col
0 True
1 False
2 True
3 False
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/420933.html
標籤:
