本文介绍了 pandas :在不知道列名的情况下重命名单个DataFrame列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我可以使用以下方式重命名单个pandas.DataFrame列:
I know I can rename single pandas.DataFrame columns with:
drugInfo.rename(columns = {'col_1': 'col_1_new_name'}, inplace = True)
但是我想在不知道列名的情况下重命名该列(基于其索引-尽管我知道字典中没有该列).我想这样重命名第1列:
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:
drugInfo.rename(columns = {1: 'col_1_new_name'}, inplace = True)
但是在DataFrame.columns字典中没有'1'条目,因此没有重命名.我怎么能做到这一点?
But in the DataFrame.columns dict there is no '1' entry, so no renaming is done. How could I achieve this?
推荐答案
应该可以:
drugInfo.rename(columns = {list(drugInfo)[1]: 'col_1_new_name'}, inplace = True)
示例:
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
索引到dataframe列属性中可能更易读:
It is probably more readable to index into the dataframe columns attribute:
df.rename(columns={df.columns[1]:'col1_new_name'}, inplace=True)
所以对你来说:
drugInfo.rename(columns = {drugInfo.columns[1]: 'col_1_new_name'}, inplace = True)
这篇关于 pandas :在不知道列名的情况下重命名单个DataFrame列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!