我需要重命名熊猫中的列,以便与预定义关键字关联的几个不同列名的标题替换为该关键字。
我希望将几个不同的潜在列名称的列表与一个关键字相关联,然后我可以将其用于以后的分组信息。在 pandas 中重命名列时,这个问题不像,因为这不能解决可以与一个关键字关联的多个列名的使用。
例如:猫,狗,鸟,鱼->被替换为标题"动物">
我正在查看重命名函数 这里 和 这里 ,但是,它似乎没有考虑到将多个列关联到要重命名的关键字的可能性。
这在熊猫身上是可以做的吗?
到目前为止,我的(无效(尝试如下:
newNames = {
'animals':['cats','dogs','fish'],
'colors':['red','blue','green']
}
DF示例:
cats dogs fish red
1 2 3 2
2 3 5 4
3 4 3 4
df.rename(index=str,columns=newNames,inplace=True)
期望的结果:
animals animals animals colors
1 2 3 2
2 3 5 4
3 4 3 4
IIUC,您可以 - 作为对许多列使用相同的名称的替代方法(这可能是一个坏主意( - 考虑使用MultiIndexing
例如:
categories = {"animals": ["cats", "dogs", "fish"],
"colors" : ["red"]}
df.columns = pd.MultiIndex.from_tuples([(k, sub) for k,v in categories.items() for sub in v])
然后你的输出将是这样的:
animals colors
cats dogs fish red
0 1 2 3 2
1 2 3 5 4
2 3 4 3 4
使用melt
创建字典
df.rename(columns=pd.DataFrame(newNames).melt().set_index('value').variable.to_dict())
Out[275]:
animals animals animals colors
0 1 2 3 2
1 2 3 5 4
2 3 4 3 4
这对你有用吗?
import pandas as pd
df = pd.DataFrame({"cats": [1, 2, 3], "dogs": [4, 5, 6], "fish": [7, 8, 9], "red": [10, 11, 12],})
# df
cats dogs fish red
0 1 4 7 10
1 2 5 8 11
2 3 6 9 12
new_names = {
"cats": "animals",
"dogs": "animals",
"fish": "animals",
"red": "colors"
}
new_df = df.rename(index=str, columns=new_names)
# new_df
animals animals animals colors
0 1 4 7 10
1 2 5 8 11
2 3 6 9 12
如果字典中未列出列new_names
则它保持不变。在这种情况下,数据框的尺寸无关紧要。
例:
df2 = pd.DataFrame({"cats": [1, 2, 3], "digs": [4, 5, 6], "fish": [7, 8, 9], "worm": [10, 11, 12], "blue": [10, 11, 12]})
# df2
cats digs fish worm blue
0 1 4 7 10 10
1 2 5 8 11 11
2 3 6 9 12 12
new_df2 = df2.rename(index=str, columns=new_names)
# new_df2
animals digs animals worm blue
0 1 4 7 10 10
1 2 5 8 11 11
2 3 6 9 12 12