[英]How to rename column names from a list in pandas?
I have about 20000 columns and i want to rename them based on "list of keywords" For example if i have df like this:我有大约 20000 列,我想根据“关键字列表”重命名它们例如,如果我有这样的 df:
df df
Column: This is a Cat Column: Dog is faithful Column: I have pigeon.
A c e
b d f
and i have list like:我有这样的清单:
pets_name = ['cat', 'Dog', 'Pigeon', 'Parrot']
I would like to have desired output where cat appear then column name should be cat.我想要在 cat 出现的地方获得所需的输出,然后列名应该是 cat。 for dog dog etc like this:对于像这样的狗狗等:
Cat Dog pigeon
A c e
b d f
Is there any way possible ?有什么办法吗?
Use str.extract
method with df.columns
and joined all values of lists with |
将str.extract
方法与df.columns
一起使用,并使用|
加入列表的所有值for regex or
:对于正则表达式or
:
pets_name = ['Cat', 'Dog', 'pigeon', 'Parrot']
df.columns = df.columns.str.extract('('+ '|'.join(pets_name) + ')', expand=False)
print (df)
Cat Dog pigeon
0 A c e
1 b d f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.