python - Pandas ,基于列值的条件列分配

标签 python pandas numpy dataframe

如何根据两列的值在 pandas by 中进行条件赋值?概念上类似于以下内容:

Column_D = Column_B / (Column_B + Column_C) if Column_C is not null else Column_C

具体例子:

import pandas as pd
import numpy as np
df = pd.DataFrame({'b': [2,np.nan,4,2,np.nan], 'c':[np.nan,1,2,np.nan,np.nan]})


     b    c
0  2.0  NaN
1  NaN  1.0
2  4.0  2.0
3  2.0  NaN
4  NaN  NaN

我想有一个新专栏d其结果是列的除法 b通过总和 bc , 如果 c不为空,否则该值应为 c 列的值. 概念上类似于以下内容:

df['d'] = df['b']/(df['b']+df['c']) if not df['c'].isnull() else df['c']

期望的结果:

     b    c         d
0  2.0  NaN       NaN
1  NaN  1.0       1.0
2  4.0  2.0       0.66
3  2.0  NaN       NaN
4  NaN  NaN       NaN

我怎样才能做到这一点?

最佳答案

试试这个(如果你想得到你想要的结果集 - 检查 b 列):

In [30]: df['d'] = np.where(df.b.notnull(), df.b/(df.b+df.c), df.c)

In [31]: df
Out[31]:
     b    c         d
0  2.0  NaN       NaN
1  NaN  1.0  1.000000
2  4.0  2.0  0.666667
3  2.0  NaN       NaN
4  NaN  NaN       NaN

或者这个,检查 c 列:

In [32]: df['d'] = np.where(df.c.notnull(), df.b/(df.b+df.c), df.c)

In [33]: df
Out[33]:
     b    c         d
0  2.0  NaN       NaN
1  NaN  1.0       NaN
2  4.0  2.0  0.666667
3  2.0  NaN       NaN
4  NaN  NaN       NaN

关于python - Pandas ,基于列值的条件列分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38643012/

相关文章:

python - Pandas 数据框按多行分组

python - python 中的 Countif() 单词

python - 用 Python 创建离线游戏排行榜

python - IPython notebook 启动问题

python - 考虑到中间的空白列,如何计算列数?

numpy - 已排序的 numpy 数组的交集

python - 在 Python 和 Django 中从 Javascript 解码 unicode

Python - Pandas 结合了两个提供不同值的数据框

python - 无法从一个日期时间列中减去另一列,减去操作不能使用类型为 dtype ('S1' ) 和 dtype ('<M8[ns]' ) 的操作数

python - 具有非重叠条目集的两列值的共现表