Pandas数学运算,以列值为条件

Bil*_*ong 4 python pandas

我需要进行一个以第二列中的值为条件的数学运算.这是设置.

给定一个简单的dataframe(df):

df = pd.DataFrame({
    'col1' : ['A', 'A', 'B', np.nan, 'D', 'C'],
    'col2' : [2, 1, 9, 8, 7, 4],
    'col3': [0, 1, 9, 4, 2, 3],
    })

In [11]: df
Out[11]: 
  col1  col2  col3
0    A     2     0
1    A     1     1
2    B     9     9
3  NaN     8     4
4    D     7     2
5    C     4     3
Run Code Online (Sandbox Code Playgroud)

我可以添加一个新的列(math)然后用基于10和的总和的数学表达式填充它col3.

df['math'] = 10 + df['col3']

In [14]: df
Out[14]: 
  col1  col2  col3  math
0    A     2     0    10
1    A     1     1    11
2    B     9     9    19
3  NaN     8     4    14
4    D     7     2    12
5    C     4     3    13
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚的是如何使表达式以另一列中的值为条件(例如,仅当col1 == B).期望的输出是:

In [14]: df
Out[14]: 
  col1  col2  col3  math
0    A     2     0   NaN
1    A     1     1   NaN
2    B     9     9    19
3  NaN     8     4   NaN
4    D     7     2   NaN
5    C     4     3   NaN
Run Code Online (Sandbox Code Playgroud)

为了补充说明,我将使用变量作为a中的col1for loop.结果,我无法.group_by()这里这里所描述的那样开始工作.我想我正在寻找这样的东西......

df['math'] = 10 + df.loc[[df['col1'] == my_var], 'col3']
Run Code Online (Sandbox Code Playgroud)

我从上面第二个例子的评论中得到了 - 但我无法让它发挥作用.它抛出了ValueError太多的值 - 也就是说,我试图将过滤器和操作列一起传递,但它只是期望过滤器. 这个 SO帖子也使用了.loc类似于我上面的表达 - 但是带有静态col1.

piR*_*red 5

where

我执行数学运算然后pandas.Series.where通过传递布尔系列来掩盖它df.col1.eq('B')

df.assign(math=df.col3.add(10).where(df.col1.eq('B')))

  col1  col2  col3  math
0    A     2     0   NaN
1    A     1     1   NaN
2    B     9     9  19.0
3  NaN     8     4   NaN
4    D     7     2   NaN
5    C     4     3   NaN
Run Code Online (Sandbox Code Playgroud)


use*_*203 5

使用loc

df['math'] = df.loc[df.col1.eq('B'), 'col3'].add(10)

  col1  col2  col3  math
0    A     2     0   NaN
1    A     1     1   NaN
2    B     9     9  19.0
3  NaN     8     4   NaN
4    D     7     2   NaN
5    C     4     3   NaN
Run Code Online (Sandbox Code Playgroud)

  • 或者 `df.loc[df.col1=="B", "math"] = df.col3+10` (2认同)