在不同条件下向pandas Dataframe添加列

时间:2018-02-16 17:09:53

标签: python pandas

我有一个pandas数据帧。

import pandas as pd
data = pd.DataFrame({
'a': [0,1,0,0,1,1,0,1], 
'b': [0,0,1,0,1,0,1,1], 
'c': [0,0,0,1,0,1,1,1],
'rate': [0,0.1,0.11,0.12,0.24,0.27,0.3,0.4]})

a,b,c是我的频道,我正在添加另一个列,通过写信显示这些频道的行总和:

data['total'] = data.a + data.b + data.c

data

    a   b   c   rate    total
1   1   0   0   0.10    1
2   0   1   0   0.11    1 
3   0   0   1   0.12    1
4   1   1   0   0.24    2
5   1   0   1   0.27    2
6   0   1   1   0.30    2
7   1   1   1   0.40    3

我想处理总数= 1且总数= 2

的数据
reduced = data[(data.a == 1) & (data.total == 2)]
print(reduced)

     a  b  c  rate  total
  4  1  1  0  0.24      2
  5  1  0  1  0.27      2

我想在这个缩小的数据框中添加列,如下所示:

      a  b  c  rate  total  prob_a  prob_b  prob_c
   4  1  1  0  0.24      2     0.1    0.11    0
   5  1  0  1  0.27      2     0.1     0      0.12

在缩小数据帧的第一行中,prob_c为0,因为C不存在(ABC => 110)。在缩小数据帧的第二行中,由于B不存在,因此prob_b为0(ABC => 101)

其中,

# Channel a alone occurs (ABC => 100)
prob_a = data['rate'][(data.a == 1) & (data.total == 1)]

# Channel b alone occurs (ABC => 010)
prob_b = data['rate'][(data.b == 1) & (data.total == 1)]

# Channel c alone occurs (ABC => 001)
prob_c = data['rate'][(data.c == 1) & (data.total == 1)]

我试过了:

reduced['prob_a'] = data['rate'][(data.a == 1) & (data.total == 1)]
reduced['prob_b'] = data['rate'][(data.b == 1) & (data.total == 1)]
reduced['prob_c'] = data['rate'][(data.c == 1) & (data.total == 1)]
print(reduced)

导致此输出:

   a  b  c  rate  total  prob_a  prob_b  prob_c
4  1  1  0  0.24      2     NaN     NaN     NaN
5  1  0  1  0.27      2     NaN     NaN     NaN

2 个答案:

答案 0 :(得分:3)

IIUC

reduced['prob_a'] = data.loc[(data.a == 1) & (data.total == 1),'rate'].values[0]
reduced['prob_b'] = data.loc[(data.b == 1) & (data.total == 1),'rate'].values[0]
reduced['prob_c'] = data.loc[(data.c == 1) & (data.total == 1),'rate'].values[0]

reduced[['prob_a','prob_b','prob_c']]=reduced[['prob_a','prob_b','prob_c']].mul(reduced[['a','b','c']].eq(1).values)
reduced
Out[698]: 
   a  b  c  rate  total  prob_a  prob_b  prob_c
4  1  1  0  0.24      2     0.1    0.11    0.00
5  1  0  1  0.27      2     0.1    0.00    0.12

答案 1 :(得分:2)

将其分为两步

<强>一
计算概率

probs = data.query('a + b + c == 1').pipe(
    lambda d: d.drop('rate', 1).T.dot(d.rate)
)

probs

a    0.10
b    0.11
c    0.12
dtype: float64

工作原理
得到总等于一行:

data.query('a + b + c == 1')

   a  b  c  rate
1  1  0  0  0.10
2  0  1  0  0.11
3  0  0  1  0.12

pipe允许我们将结果传递给函数。从上面的结果中,我想点列abc列和rate列。通过lambda的{​​{1}}允许我这样做。

更广义的方法

pipe

<强>两个
休息

df = data.copy()
rate = df.pop('rate')
mask = df.sum(1) == 1
probs = df[mask].T.dot(rate[mask])

probs