pandas 重命名没有列名的熊猫数据框的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45094138/
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 03:59:55  来源:igfitidea点击:

Renaming columns of a pandas dataframe without column names

pythonpandas

提问by tlhy

I'm trying to name the columns of my new dataframe after the dataframe.from_dict operation.

我试图在 dataframe.from_dict 操作之后命名我的新数据帧的列。

Simply using pandas.dataframe.from_dict function:

只需使用 pandas.dataframe.from_dict 函数:

df = pd.DataFrame.from_dict(my_dict,orient='index')

yields the dataframe without column headers.

产生没有列标题的数据框。

data=pd.DataFrame.from_dict(my_dict,orient='index).rename(columns = {'name','number'}) 

This yields nothing an error : TypeError: 'set' object is not callable.

这不会产生任何错误:TypeError: 'set' object is not callable。

Does anybody have a clue?

有人有线索吗?

采纳答案by snapcrack

If you want the index as the keys in your dict, you don't need to rename it.

如果您希望索引作为字典中的键,则无需重命名。

df = pd.DataFrame.from_dict(dicts, orient = 'index') #index is name

df.columns = (['number']) #non-index column is number

df.index.name = 'name'

Or instead of changing the index name you can make a new column:

或者,您可以创建一个新列,而不是更改索引名称:

df = df.reset_index() #named column becomes index, index becomes ordered sequence

df['name'] = df['index'] #new column with names

del df['index'] #delete old column

回答by Allen

You can probably do something like this by implicitly referring the columns names and then set new names.

您可以通过隐式引用列名称然后设置新名称来执行类似操作。

data = (  
  pd.DataFrame.from_dict(my_dict,orient='index')
  .rename(columns=dict(zip(df.columns,['name','number'])))
)