繁体   English   中英

如何根据在两个不同列上设置的某些条件填充 pandas dataframe 中的列?

[英]How to fill a column in pandas dataframe based on some conditions set upon two different columns?

假设我有一个如下的df:

 A     B    C
null   0   null
null   4   null
5      6   null
0      0    0

Now, I want to fill my column C based on Columns A & B condition being: only if there is a null in column A against the '0' of column B then let column C be null otherwise in all other cases copy column B to列 C。 这意味着我希望我的 df 看起来像这样:

 A     B    C
null   0   null
null   4    4
5      6    6
0      0    0

我怎样才能在 pandas 中实现这一点? 任何帮助将不胜感激,因为我在 python 和 pandas 编程方面非常新。

numpy.where与由&链接的条件用于按位与:

import numpy as np

m1 = df.A.isna()
m2 = df.B.eq(0)
df['C'] = np.where(m1 & m2, np.nan, df.B)
print (df)
     A  B    C
0  NaN  0  NaN
1  NaN  4  4.0
2  5.0  6  6.0
3  0.0  0  0.0

使用Series.fillna + Series.mask

df['C']=df['C'].fillna(df['B'].mask(df['B'].eq(0)))
print(df)

     A  B    C
0  NaN  0  NaN
1  NaN  4  4.0
2  5.0  6  6.0
3  0.0  0  0.0

或使用Series.where

df['C']=df['B'].mask(df['B'].eq(0)).where(df['C'].isnull(),df['C'])
print(df)

     A  B    C
0  NaN  0  NaN
1  NaN  4  4.0
2  5.0  6  6.0
3  0.0  0  0.0

使用fillna并检查A + B > 0 ,如果是,则使用locB填充C

mask = df['A'].fillna(0) + df['B'] > 0
df.loc[mask, 'C'] = df['B']
     A  B    C
0  NaN  0  NaN
1  NaN  4  4.0
2  5.0  6  6.0
3  0.0  0  0.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM