Python 数据框,从列表中设置索引

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

dataframe, set index from list

pythonpandas

提问by vandelay

Is it possible when creating a dataframe from a list, to set the index as one of the values?

从列表创建数据框时是否可以将索引设置为值之一?

import pandas as pd

tmp = [['a', 'a1'], ['b',' b1']]

df = pd.DataFrame(tmp, columns=["First", "Second"])

        First  Second
0          a   a1
1          b   b1

And how I'd like it to look:

我希望它看起来如何:

        First  Second
a          a   a1
b          b   b1

采纳答案by Alexander

>>> pd.DataFrame(tmp, columns=["First", "Second"]).set_index('First', drop=False)
      First Second
First             
a         a     a1
b         b     b1

回答by ragesz

If you don't want index name:

如果您不想要索引名称:

df = pd.DataFrame(tmp, columns=["First", "Second"], index=[i[0] for i in tmp])

Result:

结果:

  First Second
a     a     a1
b     b     b1

回答by Aman Singh Kamboj

Change it to list before assigning it to index

在将其分配给索引之前将其更改为列表

df.index = list(df["First"])