字典名称字典键和值使用pandas
我正在使用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
另一个解决scheme:
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中的列名,可能的解决scheme:
#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)