首页 文章

在Python字典中重命名Pandas列

提问于
浏览
1

我是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 DataFrames .

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

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”,“值”和其他几个作为当前列名 .

我尝试过使用我能想到的每一种组合 . 我的结局很快 . 非常感谢帮助我完成这项工作 .

谢谢,杰里米

2 回答

  • 0

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

    #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'
    
  • 0

    您可能需要考虑使用 Pandas.Panel 对象,而不是存储 DataFrames 的字典 . 这应该工作:

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

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

相关问题