Pandas PCT在2列之间更改,更换原始
(我认为)我希望通过与一个静态列相比查找%变化来将变换
应用于列。
我的第一次尝试看起来像这样(没有转换):
from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
print(df)
for col in df.columns:
# Find the % increase/decrease of "col" compared to column A
df[col] = df[["A", col]].pct_change(axis=1)[col]
print(df)
...但是,当我期望它以%增加/降低格式时,由此产生的DF就是NAN。
因此,例如,它首先将A列与A列进行比较,这是很好的,所有值都应相同。然后,下一个迭代应与A列A相比。最后,我们应该在B列中看到%s。然后对于C和D。我只是新手转换为适当的列的/更改值,并且不确定该如何做。
(I think) I'm looking to apply a transform
to a column, by finding the % change when compared to one static column.
My first attempt looks like this (without a transform):
from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
print(df)
for col in df.columns:
# Find the % increase/decrease of "col" compared to column A
df[col] = df[["A", col]].pct_change(axis=1)[col]
print(df)
...however the resulting df is all NaN's when I'm expecting it to be in % increase/decrease format.
So as an example, it starts by comparing column A with column A, that's fine, all values SHOULD be the same. Then the next iteration it should be column B compared to column A. We should see %'s in column B in the end. Then same for C and D. I'm just new to transforms/changing values of a column in place and not sure how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从数据框架中减去列 a 然后除以列
a
以计算pct_change:上述表达式可以进一步简化为:
Subtract column
A
from the dataframe then divide by columnA
to calculate pct_change:The above expression can be further simplied to:
我认为问题是您不能在
df [[“ A”,col]]
中拥有两个列“ A”。当您将df.columns
更改为df.columns [1:]
时,它会在没有错误的情况下运行。结果:
I think the problem is that you can not have two columns 'A' in
df[["A", col]]
. When you changedf.columns
todf.columns[1:]
it runs without errors.Result: