简体   繁体   English

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

[英]Pandas: Rename single DataFrame column without knowing column name

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. 但是在DataFrame.columns dict中没有'1'条目,因此不进行重命名。 How could I achieve this? 我怎么能实现这个目标?

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: 索引到dataframe columns属性可能更具可读性:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM