使用特定列条件添加行

问题描述 投票:0回答:2

我有一个值为 a 和 b 的列值,只为 b 添加一行值并创建一个新列

value    val1    val2  val3

a         1       2     0

b         3       4     5

a         3       0     0

b         3       4     0

我期待输出

value  val1  val2  val3  total_a  total_b

a        1     2     0     3        
b       3     4     5               12

a       3     0     0     3                  
b       3     4     0               7

我试过的代码

df['total_b']=df['value'].str.contains('b').apply(np.sum,axis=1)

但是抛出一个错误,没有 0 的维度

请尝试解决这个问题

提前致谢。

python pandas dataframe
2个回答
2
投票

你可以试试这个:

df['total_a'] = df.query('value == "a"').sum(1, numeric_only=True)
df['total_b'] = df.query('value == "b"').sum(1, numeric_only=True)

输出:

  value  val1  val2  val3  total_a  total_b
0     a     1     2     0      3.0      NaN
1     b     3     4     5      NaN     12.0
2     a     3     0     0      3.0      NaN
3     b     3     4     0      NaN      7.0

或者在分配列时使用循环使其通用:

for val in ["a", "b"]:
    df[f"total_{val}"] = df.query(f'value == "{val}"').sum(1, numeric_only=True)

0
投票

另一种选择:

df=pd.DataFrame({'value':['a', 'b', 'a', 'b'], 'val1':[1, 3, 3, 3], 'val2':[2, 4, 0, 4], 'val3':[0,5,0,0]})

df['total_a']=df.loc[df['value']=='a',['val1' , 'val2', 'val3']].sum(axis = 1)
df['total_b']=df.loc[df['value']=='b',['val1' , 'val2', 'val3']].sum(axis = 1)

df.fillna('') # not recommended, put it only to match your desired output

输出:

  value  val1  val2  val3 total_a total_b
0     a     1     2     0     3.0        
1     b     3     4     5            12.0
2     a     3     0     0     3.0        
3     b     3     4     0             7.0
© www.soinside.com 2019 - 2024. All rights reserved.