Skip to main content
 首页 » 编程设计

python之使用 Pandas 的字典键和值的列名称

2025年02月15日13lexus

我正在使用 pandas 将一些数据转储到 excel 文件中。数据为字典格式,我使用以下代码转储它。

df1 = pd.DataFrame.from_dict(weights_dict, orient="index") 
df1.columns = ['weights'] 

我得到以下输出

             | weights 
------------------------ 
D1_sum       |  8 
U2_conv      |  9 
y1_maxpool   |  10 
y22_dropout  |  11 

我也想为第一列设置一个名称。我怎样才能做到这一点?谢谢。

预期输出:

  Layers     | weights 
------------------------ 
D1_sum       |  8 
U2_conv      |  9 
y1_maxpool   |  10 
y22_dropout  |  11 

编辑:

使用后

df.index.name = 'Layer' 

我得到以下结果:

             | weights 
------------------------ 
Layer        | 
------------------------ 
D1_sum       |  8 
U2_conv      |  9 
y1_maxpool   |  10 
y22_dropout  |  11 

使用 rename_axis 会出现以下错误:

 File "C:\ENV\p34\lib\site-packages\pandas\core\generic.py", line 573, in rename 
    result._data = result._data.rename_axis(f, axis=baxis, copy=copy) 
  File "C:\ENV\p34\lib\site-packages\pandas\core\internals.py", line 2233, in rename_axis 
    obj.set_axis(axis, _transform_index(self.axes[axis], mapper)) 
  File "C:\ENV\p34\lib\site-packages\pandas\core\internals.py", line 3982, in _transform_index 
    items = [func(x) for x in index] 
  File "C:\ENV\p34\lib\site-packages\pandas\core\internals.py", line 3982, in <listcomp> 
    items = [func(x) for x in index] 
TypeError: 'str' object is not callable 

请您参考如下方法:

您可以使用设置列名称或索引名称或两者:

df = pd.DataFrame({'weights': [8, 9, 10, 11]},  
                   index=['D1_sum', 'U2_conv', 'y1_maxpool', 'y22_dropout'])  
print (df) 
             weights 
D1_sum             8 
U2_conv            9 
y1_maxpool        10 
y22_dropout       11 
 
 
df.index.name = 'Layers1' 
df.columns.name = 'Layers2' 
 
print (df) 
Layers2      weights 
Layers1              
D1_sum             8 
U2_conv            9 
y1_maxpool        10 
y22_dropout       11 

另一种解决方案 rename_axis :

df = df.rename_axis('Layers1').rename_axis('Layers2', axis=1) 
 
print (df) 
Layers2      weights 
Layers1              
D1_sum             8 
U2_conv            9 
y1_maxpool        10 
y22_dropout       11 

df.columns.name = 'Layers' 
print (df) 
Layers       weights 
D1_sum             8 
U2_conv            9 
y1_maxpool        10 
y22_dropout       11 
 
df = df.rename_axis('Layers', axis=1) 
print (df) 
Layers       weights 
D1_sum             8 
U2_conv            9 
y1_maxpool        10 
y22_dropout       11 

如果在 Excel 中需要列名,可能的解决方案:

#set index name 
df.index.name = 'Layer' 
#reset index - index values create new column 
df = df.reset_index() 
print (df) 
         Layer  weights 
0       D1_sum        8 
1      U2_conv        9 
2   y1_maxpool       10 
3  y22_dropout       11 
 
#write df to excel, remove default index (0,1,2,3) 
df.to_excel('file.xlsx', index=False)