[英]Inplace operation on masked dataframe
I'm a bit of noob with pandas and I'm trying to perform some calculations and modifications on parts of a masked dataframe using apply
. 我和pandas有点混蛋,我正在尝试使用
apply
对掩码数据帧的某些部分进行一些计算和修改。 The part I want to operate on is defined by my mask and I don't want to modify any non-masked values. 我想要操作的部分是由我的掩码定义的,我不想修改任何非掩码值。
The thing is that I have no idea what is the proper way to put the result of the apply
call on the masked dataframe back where it belongs in the original dataframe (or a copy of it, doesn't matter). 问题是,我不知道将
apply
调用的结果放在掩码数据帧的正确数据帧(或其副本,无关紧要)的正确方法是什么。
Here is a toy example of what I'm struggling with, I will try to make all values in the A
column negative using a mask and apply: 这是我正在努力的一个玩具示例,我将尝试使用蒙版使
A
列中的所有值为负并应用:
import pandas as pd
import numpy as np
def make_df():
np.random.seed(4)
df = pd.DataFrame(np.random.randn(5, 2),columns=["A","B"])
return df
df = make_df()
mask = (df["A"]>0)
print(df)
A B
0 0.050562 0.499951
1 -0.995909 0.693599
2 -0.418302 -1.584577
3 -0.647707 0.598575
4 0.332250 -1.147477
The expected result is this : 预期的结果是这样的:
A B
0 -0.050562 0.499951
1 -0.995909 0.693599
2 -0.418302 -1.584577
3 -0.647707 0.598575
4 -0.332250 -1.147477
What I hoped would work was this : 我希望能起作用的是:
df = make_df()
df[mask]["A"] = df[mask]["A"].apply(lambda v: -v)
print(df)
A B
0 0.050562 0.499951
1 -0.995909 0.693599
2 -0.418302 -1.584577
3 -0.647707 0.598575
4 0.332250 -1.147477
But it fails with pandas warning me that df[mask]["A"]
is a copy not a view so modifications on it do not affect df
. 但它失败了,熊猫警告我
df[mask]["A"]
是一个副本而不是一个视图,因此对它的修改不会影响df
。
Try to use loc[]
: 尝试使用
loc[]
:
In [11]: df.loc[mask, 'A'] *= -1
In [12]: df
Out[12]:
A B
0 -0.050562 0.499951
1 -0.995909 0.693599
2 -0.418302 -1.584577
3 -0.647707 0.598575
4 -0.332250 -1.147477
你可以试试:
df.loc[df['A'] > 0,'A'] = -df.A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.