Python 如何在熊猫中设置第一列和第一行作为索引?

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

How to set in pandas the first column and row as index?

pythonpython-3.xpandas

提问by Oli

When I read in a CSV, I can say pd.read_csv('my.csv', index_col=3)and it sets the third column as index.

当我读入 CSV 文件时,我可以说pd.read_csv('my.csv', index_col=3)并将第三列设置为索引。

How can I do the same if I have a pandas dataframe in memory? And how can I say to use the first row also as an index? The first column and row are strings, rest of the matrix is integer.

如果我的内存中有一个 Pandas 数据框,我该怎么做?我怎么能说将第一行也用作索引?第一列和第一行是字符串,矩阵的其余部分是整数。

回答by Y. Yazarel

You can try this regardless of the number of rows

无论行数如何,您都可以尝试

df= pd.read_csv('data.csv', index_col=0)

df= pd.read_csv('data.csv', index_col=0)

回答by Annie Guo

Maybe try set_index()?

也许试试 set_index()?

df = df.set_index([2])

回答by villasv

Making the first (or n-th) column the index in increasing order of verboseness:

按详细程度递增的顺序将第一列(或第 n 列)作为索引:

df.set_index(list(df)[0])
df.set_index(df.columns[0])
df.set_index(df.columns.tolist()[0])

Making the first (or n-th) row the index:

将第一行(或第 n 行)作为索引:

df.set_index(df.iloc[0].values)

You can use both if you want a multi-level index:

如果你想要一个多级索引,你可以同时使用两者:

df.set_index([df.iloc[0], df.columns[0]])

Observe that using a column as index will automatically drop it as column. Using a row as index is just a copy operation and won't drop the row from the DataFrame.

请注意,使用列作为索引会自动将其删除为列。使用一行作为索引只是一个复制操作,不会从 DataFrame 中删除该行。