我试图弄清楚如何在具有布尔条件的数据框中添加数据。
数据如下:
Col1 Col2 Col3
0 A 1 Data
1 B 2 Data
2 A 3 NaN
理想情况下,我将在Python循环中运行此代码,以填充字典中的数据。
我写的代码是
df["Column 3"].loc[df["Column 1"] == "Loop Variable"].isna()
这会给我一个数组,其中索引0为False,索引2为True。
0 False
2 True
Name: Column 3, dtype: bool
在继续下一个变量之前,如何忽略索引0,将数据填充到索引2中?
编辑: 我的问题被标记为重复,所以我尝试了另一个问题上建议的代码。
这是结果。
mask = df["Column 3"].loc[df["Column 1"] == "Loop Variable"].isna()
column = "Column 3"
df.loc[mask, column] = 13
IndexingError: (2 True
12 False
Name: 'Column 3', dtype: bool, 'Column 3')
我也尝试过这个。
df['Column 3'] = np.where(mask, Data, df["Column 3"])
ValueError: operands could not be broadcast together with shapes (2,) () (20,)
还有这个。
df.loc[mask, column] = Data
IndexingError: (2 True
12 False
Name: Column 3, dtype: bool, 'Column 3`')
我在该页面上尝试了其他代码。但是他们给出了其他错误。在这里打印它们将是重复的。 他们都是一样的。值的长度与索引的长度不符
基于错误,我认为此代码不符合我的目的?
编辑2: 我知道了。
df["Coulmn 3"].loc[(df["Col 1"] == "Loop Variable") & (df["Col 3"].isna())] = Data