我尝试更新三列中的值。逻辑是:如果列中的特定行为空,我想将其更改为 n 而不是 无。如果它有一个值,那么我想将该值更改为 y。示例如下:
Current data:
barcode dash_1 dash_2 dash_3
ABC123 ABC123 ABC123 None
ABC124 ABC124 ABC124 ABC124
ABC125 None ABC125 ABC125
ABC126 ABC126 None None
Desired output:
barcode dash_1 dash_2 dash_3
ABC123 y y n
ABC124 y y y
ABC125 n y y
ABC126 n n n
我一直在尝试执行类似于下面代码的操作,但我收到消息 str object has no attribute isnull。任何想法我做错了什么?谢谢!
for idx, row in barcodes2.iterrows():
for col in ['dash_1','dash_2','dash_3']:
if row[col].isnull():
row[col] == 'n'
else:
row[col] == 'y'
请您参考如下方法:
您可以使用 df.notnull() 和 df.isnull() 设置所有值:
df[df.notnull()] = 'y'
df[df.isnull()] = 'n'
例子:
>>> df
barcode dash_1 dash_2 dash_3
0 ABC123 ABC123 ABC123 None
1 ABC124 ABC124 ABC124 ABC124
2 ABC125 None ABC125 ABC125
3 ABC126 ABC126 None None
现在:
>>> df[df.notnull()] = 'y'
>>> df[df.isnull()] = 'n'
>>> df
barcode dash_1 dash_2 dash_3
0 y y y n
1 y y y y
2 y n y y
3 y y n n
