使用 Pandas 的字典键和值的列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42135687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:56:17  来源:igfitidea点击:

Columns name for dictionary key and values using Pandas

pythonexcelpandas

提问by blackbug

I am using pandas to dump some data into excel file. The data is in dictionary format and I am using the following code to dump it.

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

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

I am getting the following output

我得到以下输出

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

I want to set a name to the first column as well. How can I do that? Thanks.

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

Expected output:

预期输出:

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

EDIT:

编辑:

After using

使用后

df.index.name = 'Layer'

I get the following result:

我得到以下结果:

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

Using the rename_axis gives following error:

使用 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

采纳答案by jezrael

You can use set columns names or index name or both:

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

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

Another solution with rename_axis:

另一个解决方案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

Possible solution if need column name in Excel:

如果需要 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)