简体   繁体   English

对同一数据帧的不同部分进行操作

[英]Operations with different parts of the same dataframe

Assume there is a dataframe: 假设有一个数据帧:

    kind  value
0      1      1
1      1      2
2      1      3
3      1      4
4      1      5
5      2      6
6      2      7
7      2      8
8      2      9
9      2      10

We can do something with a filtered part of a dataframe: 我们可以对数据帧的过滤部分执行某些操作:

df.loc[df['kind']==1, 'value'] = df.loc[df['kind']==1, 'value'] * 2

How to perform a calculation involving two or more parts of the same dataframe, assuming their size is equal? 假设它们的大小相等,如何执行涉及同一数据帧的两个或多个部分的计算? Something like this: 像这样的东西:

df.loc[df['kind']==1, 'value'] = 
    df.loc[df['kind']==1, 'value'] * df.loc[df['kind']==2, 'value']

(this doesn't work) (这不起作用)

Try this: 试试这个:

In [107]: df.loc[df['kind']==1, 'value'] *= df.loc[df['kind']==2, 'value'].values

In [108]: df
Out[108]:
   kind  value
0     1      6
1     1     14
2     1     24
3     1     36
4     1     50
5     2      6
6     2      7
7     2      8
8     2      9
9     2     10

Use: 使用:

m = df['kind']==1
df.loc[m, 'value'] = df.loc[m, 'value'].values * df.loc[df['kind']==2, 'value'].values
print (df)
   kind  value
0     1      6
1     1     14
2     1     24
3     1     36
4     1     50
5     2      6
6     2      7
7     2      8
8     2      9
9     2     10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM