重命名 Python 字典中的 Pandas 列

Rename Pandas column inside Python dictionary

我是 Pandas/Python 的新手,遇到了麻烦。我有一个字典对象,"dict" 看起来像:

In[107]:dict
Out[107]: 
{'Thing1':
 Date
 2014-09-15        0.12
 2014-09-15        0.17
 2014-09-16        0.57
 dtype: float64,

'Thing2':
 Date
 2014-11-10    30.00
 2014-12-26    25.00
 2014-12-29    30.00
 dtype: float64,

 'Thing3'
 Date
 2014-09-26      61.80
 2014-09-30     151.58
 2014-10-06     749.87
 dtype: float64}

"Thing1"、"Thing2" 和 "Thing3" 是具有日期时间索引 "Date".

的 Pandas DataFrame

我想重命名未命名的 "zero" 列,以便我的数据看起来像这样:

In[107]:dict
Out[107]: 
{'Thing1':
 Date              New Title
 2014-09-15        0.12
 2014-09-15        0.17
 2014-09-16        0.57
 dtype: float64,

'Thing2':
 Date          New Title
 2014-11-10    30.00
 2014-12-26    25.00
 2014-12-29    30.00
 dtype: float64,

 'Thing3'
 Date           New Title
 2014-09-26      61.80
 2014-09-30     151.58
 2014-10-06     749.87
 dtype: float64}

我正在使用 for 循环来创建这本词典。当我循环时,我添加 "Thing1",然后添加 "Thing2",最后添加 "Thing3"。我想重命名该列或在创建它时为其命名。我专注于尝试重命名该列。以下是我一直在尝试的示例...

我很确定我的问题是我不知道如何在字典中建立索引。我尝试了以下各种排列:

dict["Thing{0}".format(x)].rename(index=Earn_Cumulative["Thing{0}".format(x)], columns={0:"New Title"})

我试过使用和不使用索引。我已经尝试使用“”、“0”、"value" 和其他几个作为当前列名。

我试过使用我能想到的每一种组合。我已经筋疲力尽了。非常感谢帮助我完成这个过程。

谢谢, 杰里米

与其存储 DataFrames 的字典,不如考虑使用 Pandas.Panel 对象。这应该有效:

for df in dict.values:
    df['Date'] = 'new data'

数据帧通过引用存储在字典中,因此当它们在字典中时覆盖它们的数据应该不需要创建新字典或任何东西。

这是一些代码,用于重命名存储在 dict 中的数据帧的列:

#create a frame with a timeseries index and a unnamed column
rng = pd.DatetimeIndex(pd.to_datetime(['1/1/2014','1/2/2014','1/2/2014', '1/3/2014', '1/3/2014','1/4/2014','1/6/2014']))
df = pd.DataFrame({None:[5,6,7,8,2,3,6],'date':rng})
df.set_index('date', inplace=True)

# add frames to dict
frames ={}
for i in range(3):
    frames[i] = df

使用参数 inplace=True 确保框架在原地作用:

#loop through dicts using keys and rename column names in place
for k in frames.keys():
    frames[k].rename(columns=({None:'Something'}), inplace=True)

如果他们实际上 seriesdict 中:

series_dict ={}
for i in range(3):
    series_dict[i] = df[None]

要命名一个系列,您只需分配给 name:

for k in frames.keys():
    series_dict[k].name = 'New_Name'