Python 重命名未命名的列熊猫数据框

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

Rename unnamed column pandas dataframe

pythonpandascsv

提问by user2491254

My csv file has no column name for the first column, and I want to rename it. Usually, I would do data.rename(columns={'oldname':'newname'}, inplace=True), but there is no name in the csv file, just ''.

我的 csv 文件第一列没有列名,我想重命名它。通常,我会这样做data.rename(columns={'oldname':'newname'}, inplace=True),但是 csv 文件中没有名称,只有 ''.

回答by TomAugspurger

It has a name, the name is just ''(the empty string).

它有一个名字,名字就是''(空字符串)。

In [2]: df = pd.DataFrame({'': [1, 2]})

In [3]: df
Out[3]: 

0  1
1  2

In [4]: df.rename(columns={'': 'A'})
Out[4]: 
   A
0  1
1  2

回答by KyungHoon Kim

When you load the csv, use the option 'index_col' like

加载 csv 时,请使用“index_col”选项,例如

pd.read_csv('test.csv', index_col=0)

index_col : int or sequence or False, default None Column to use as the row labels of the DataFrame. If a sequence is given, a MultiIndex is used. If you have a malformed file with delimiters at the end of each line, you might consider index_col=False to force pandas to notuse the first column as the index (row names)

index_col : int 或 sequence 或 False,默认 None 列用作 DataFrame 的行标签。如果给出序列,则使用 MultiIndex。如果您有一个格式错误的文件,每行末尾都有分隔符,您可以考虑 index_col=False 强制熊猫使用第一列作为索引(行名称)

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.read_csv.html

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.read_csv.html

回答by Marco

You can view the current dataframe using data.head()

您可以使用查看当前数据框 data.head()

if that returns 'Unnamed: 0'as the column title, you can rename it in the following way:

如果它'Unnamed: 0'作为列标题返回,您可以按以下方式重命名它:

data.rename( columns={'Unnamed: 0':'new column name'}, inplace=True )

回答by ambrish dhaka

The solution can be improved as data.rename( columns={0 :'new column name'}, inplace=True ). There is no need to use 'Unnamed: 0', simply use the column number, which is 0in this case and then supply the 'new column name'.

该解决方案可以改进为data.rename( columns={0 :'new column name'}, inplace=True )。无需使用'Unnamed: 0',只需使用列号,0在本例中为列号,然后提供'new column name'.

回答by saccpp

Try the below code,

试试下面的代码,

df.columns = [‘A', ‘B', ‘C', ‘D']

df.columns = [‘A', ‘B', ‘C', ‘D']

回答by tsveti_iko

It can be that the first column/row could not have a name, because it's an index and not a column/row. That's why you need to rename the index like this:

可能是第一列/行没有名称,因为它是索引而不是列/行。这就是为什么你需要像这样重命名索引:

df.index.name = 'new_name'