动态地向pandas数据框中添加列

动态地向pandas数据框中添加列

本文介绍了动态地向pandas数据框中添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为'a','b',...,'n'的大熊猫数据框。



每日更改列,并将数据框扩展为:'a','b',...,'n','a_daily','b_daily',...,'n_daily_change'。



我尝试了以下代码(它提供了KeyError:'column_names'):

  df中的column_names:
df [str(column_names)+'_daily'] = df ['column_names']。pct_change(freq = 1).fillna(0)
/ pre>

为了使其工作,需要更改什么?

解决方案

您只需传递列名称,而不是以字符串形式传递:

  for df中的column_names:
df [str(column_names)+'_daily'] = df [column_names] .pct_change(freq = 1).fillna(0)

此外,我认为您不需要将列名重新转到 str

  for df中的column_names 
df [column_names +'_daily]] = df [column_names] .pct_change(freq = 1).fillna(0)

应该可以工作。



所以错误得到提升,因为 df ['column_names'] 不存在,iterable是列名称,因此将其作为密钥才能正常工作


I have a pandas dataframe with column names 'a', 'b', ...,'n'.

for each column I want to show the daily change for the columns and extend the dataframe to consist of: 'a','b',...,'n','a_daily', 'b_daily', ...,'n_daily_change'.

I tried the following code (which gives KeyError: 'column_names'):

for column_names in df:
    df[str(column_names) + '_daily'] = df['column_names'].pct_change(freq=1).fillna(0)

What do I need to change in order for it to work?

解决方案

You need to pass the column name only not as a string:

for column_names in df:
    df[str(column_names) + '_daily'] = df[column_names].pct_change(freq=1).fillna(0)

Also I think you don't need to cast the column name back to str again:

for column_names in df:
    df[column_names + '_daily'] = df[column_names].pct_change(freq=1).fillna(0)

should work.

So the error gets raised because df['column_names'] doesn't exist, the iterable are the column names so passing this as the key will just work

这篇关于动态地向pandas数据框中添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:25