pandas 重命名列(如果包含字符串) [英] pandas rename column if contains string
本文介绍了 pandas 重命名列(如果包含字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想遍历数据帧中的所有列,并在它们包含某些字符串的情况下重命名(或映射)列.
I would like to go through all the columns in a dataframe and rename (or map) columns if they contain certain strings.
例如:用字符串"agri"重命名所有包含"agriculture"的列
For example: rename all columns that contain 'agriculture' with the string 'agri'
我正在考虑使用rename
和str.contains
,但无法弄清楚如何将它们组合起来以达到我想要的目的.
I'm thinking about using rename
and str.contains
but can't figure out how to combine them to achieve what i want.
推荐答案
You can use str.replace
to process the columns first, and then re-assign the new columns back to the DataFrame:
import pandas as pd
df = pd.DataFrame({'A_agriculture': [1,2,3],
'B_agriculture': [11,22,33],
'C': [4,5,6]})
df.columns = df.columns.str.replace('agriculture', 'agri')
print df
输出:
A_agri B_agri C
0 1 11 4
1 2 22 5
2 3 33 6
这篇关于 pandas 重命名列(如果包含字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文