gpt4 book ai didi

python - 在 Pandas 列重命名中的 For 循环中引用项目

转载 作者:行者123 更新时间:2023-11-30 22:36:29 25 4
gpt4 key购买 nike

我有两个 pandas.DataFrame,我希望将两个都存在的名为 value 的列重命名为数据框的名称:

#Debt level relative to currency strength
#preamble
import pandas as pd
import statsmodels.formula.api as sm #check that this is actually used
import os
import numpy as np

os.chdir('C:\\Users\\pineapple\\Desktop')

#function construction
def loader(y):
return pd.read_csv(y, header='infer', encoding="ISO-8859+-1")

def viewer(x):
print(x.ix[:])

def delrow(x,y):
return x[pd.notnull(x[y])]

#
names = ['currency', 'debt_ratio']

for i in names:
i = loader(''+i+'.csv') #load data
i = i.replace('..', np.NaN)

for x in range(2007,2015):
y = str(x)
print(y)
i=delrow(i, '' + y + ' [YR'+y+']') #deletes missing values
i.rename(columns = {'' + y + ' [YR'+y+']': ''+ y +''}, inplace=True) #rename columns

i = i.drop(['Series Name','Series Code', 'Country Name', \
'1990 [YR1990]', '2000 [YR2000]' ], axis = 1)

i = pd.melt(i, id_vars=['Country Code'],value_vars=['2007','2008','2009','2010','2011', \
'2012','2013','2014']) #reshape

i.rename(columns={'variable':'year', 'Country Code':'code'}, inplace=True)
viewer(i)

eval(i).rename(columns={'value':i}, inplace=True) #breaks here

i['id'] = i['code'] + i['year']

#output
viewer(i)

这不起作用 - 它无法更新 value 列并弄乱数据帧的格式。

最佳答案

更改:

for i in names:
i = loader(''+i+'.csv') #load data

致:

for name in names:
i = loader(name + '.csv') #load data

然后使用以下命令重命名:

i.rename(columns={'value':name}, inplace=True)

关于python - 在 Pandas 列重命名中的 For 循环中引用项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44147917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com