pandas 设置一个字符串作为pandas DataFrame 的索引

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

Set a string as index of pandas DataFrame

pythonpandasdataframeindexing

提问by gabboshow

Given the dataframe df

给定数据框 df

df = pd.DataFrame([1,2,3,4])
print(df)
   0
0  1
1  2
2  3
3  4

I would like to modify it as

我想将其修改为

print(df)
   0
A  1
A  2
A  3
A  4

回答by Brad Solomon

In this specific case you can use:

在这种特定情况下,您可以使用:

df.index = ['A'] * len(df)

回答by Zero

Use set_index

set_index

In [797]: df.set_index([['A']*len(df)], inplace=True)

In [798]: df
Out[798]:
   0
A  1
A  2
A  3
A  4

回答by YOBEN_S

When you create the df, you can add it.

创建 df 时,可以添加它。

df = pd.DataFrame([1,2,3,4],index=['A']*4)
df
Out[325]: 
   0
A  1
A  2
A  3
A  4