Pandas:在不知道列名的情况下重命名单个 DataFrame 列

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

Pandas: Rename single DataFrame column without knowing column name

pythonpandas

提问by afrendeiro

I know I can rename single pandas.DataFrame columns with:

我知道我可以重命名单个 pandas.DataFrame 列:

drugInfo.rename(columns = {'col_1': 'col_1_new_name'}, inplace = True)

But I'd like to rename a column without knowing its name (based on its index - although I know dictionaries don't have it). I would like rename column number 1 like this:

但是我想在不知道名称的情况下重命名列(基于其索引 - 尽管我知道字典没有它)。我想像这样重命名第 1 列:

drugInfo.rename(columns = {1: 'col_1_new_name'}, inplace = True)

But in the DataFrame.columns dict there is no '1' entry, so no renaming is done. How could I achieve this?

但是在 DataFrame.columns dict 中没有“1”条目,因此没有重命名。我怎么能做到这一点?

回答by EdChum

Should work:

应该管用:

drugInfo.rename(columns = {list(drugInfo)[1]: 'col_1_new_name'}, inplace = True)

Example:

例子:

In [18]:

df = pd.DataFrame({'a':randn(5), 'b':randn(5), 'c':randn(5)})
df
Out[18]:
          a         b         c
0 -1.429509 -0.652116  0.515545
1  0.563148 -0.536554 -1.316155
2  1.310768 -3.041681 -0.704776
3 -1.403204  1.083727 -0.117787
4 -0.040952  0.108155 -0.092292
In [19]:

df.rename(columns={list(df)[1]:'col1_new_name'}, inplace=True)
df
Out[19]:
          a  col1_new_name         c
0 -1.429509      -0.652116  0.515545
1  0.563148      -0.536554 -1.316155
2  1.310768      -3.041681 -0.704776
3 -1.403204       1.083727 -0.117787
4 -0.040952       0.108155 -0.092292

It is probably more readable to index into the dataframe columns attribute:

索引到数据框列属性可能更具可读性:

df.rename(columns={df.columns[1]:'col1_new_name'}, inplace=True)

So for you:

所以对你来说:

drugInfo.rename(columns = {drugInfo.columns[1]: 'col_1_new_name'}, inplace = True)