Ste*_*son 1 python subset dataframe pandas
我正在尝试修改列中的特定值,其中修改使用另一列中的值。例如说我有一个 df:
A B C
1 3 8
1 6 8
2 2 9
2 6 1
3 4 5
3 6 7
Run Code Online (Sandbox Code Playgroud)
我df['B'] = df['B'] + df['C']只想要子集的地方df.loc[df['A'] == 2]
生产:
A B C
1 3 8
1 6 8
2 11 9
2 7 1
3 4 5
3 6 7
Run Code Online (Sandbox Code Playgroud)
我努力了
df.loc[(df['A']==2), 'B'].apply(lambda x: x + df['C'])
但得到:
InvalidIndexError:重新索引仅对具有唯一值的索引对象有效
您很接近,无需申请:
m = df['A'] == 2
#short way
df.loc[m, 'B'] += df.loc[m, 'C']
#long way
df.loc[m, 'B'] = df.loc[m, 'B'] + df.loc[m, 'C']
Run Code Online (Sandbox Code Playgroud)
或者:
df.loc[df['A'] == 2, 'B'] += df['C']
Run Code Online (Sandbox Code Playgroud)