pandas 如何将未命名的列设置为索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45999604/
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
How do I set an unnamed column as the index?
提问by DanONS
In all the examples I have found, a column name is usually required to set it as the index
在我发现的所有例子中,通常需要一个列名来将其设置为索引
Instead of going into excel to add a column header, I was wondering if it's possible to set an empty header as the index. The column has all the values I want included, but lacks a column name:
我没有进入 excel 添加列标题,而是想知道是否可以将空标题设置为索引。该列包含我想要包含的所有值,但缺少列名:
My script is currently:
我的脚本目前是:
import pandas as pd
data = pd.read_csv('file.csv')
data
采纳答案by StefanK
You don't need to rename the first column in excel. It's as easy in pandas as well:
您不需要重命名 Excel 中的第一列。在Pandas中也很简单:
new_columns = data.columns.values
new_columns[0] = 'Month'
data.columns = new_columns
Afterwards, you can set the index:
之后,您可以设置索引:
data = data.set_index('Month')
回答by Kyle
You could also just select the column by id with iloc
:
您也可以通过 id 选择列iloc
:
data = data.set_index(data.iloc[:, 0])
Or when you call pd.read_csv()
, specify index_col
:
或者当你打电话时pd.read_csv()
,指定index_col
:
data = pd.read_csv('path.csv', index_col=0)
回答by whateveros
When I have encountered columns missing names, Pandas always name them 'Unnamed: n', where n = ColumnNumber-1. ie 'Unnamed: 0' for first column, 'Unnamed: 1' for second etc. So I think that in your case the following code should be useful:
当我遇到缺少名称的列时,Pandas 总是将它们命名为“未命名:n”,其中 n = ColumnNumber-1。即第一列的“未命名:0”,第二列的“未命名:1”等。所以我认为在您的情况下,以下代码应该有用:
# set your column as the dataframe index
data.index = data['Unnamed: 0']
# now delete the column
data.drop('Unnamed: 0', axis=1, inplace=True)
# also delete the index name which was 'Unnamed: 0' obviously
del data.index.name
回答by Kirti Nikam
You can do as follows:
您可以执行以下操作:
import pandas as pd
data = pd.read_csv('file.csv',index_col=0)
data