我有 4 个不同的 dfs。 列名示例:
df1 = a1, b1, c1, d1
df2 = b1, c1, e1
df3 = a1, b1, c1
我创建了这样的字典:
dict = {a1:art1, b1:base1, c1:cell1, d1:dan1, e1:el1}
可以不使用 for 循环重命名列吗?我的意思是,我试图通过在 for 循环中重命名函数来做到这一点,但随后我需要遍历所有数据帧,它在代码中看起来不太好,而且我认为它没有应有的那么快。
我的预期结果是:
df1 = art1, base1, cell1, dan1
df2 = base1, cell1, el1
df3 = art1, base1, cell1
我在堆栈上找到了一些答案,但没有任何适合我的问题,我有一本字典和很少有列名不唯一的 df。
答案 0 :(得分:3)
理解:
d = {'a1': 'art1', 'b1': 'base1', 'c1': 'cell1', 'd1': 'dan1', 'e1': 'el1'}
df1, df2, df3 = [df.rename(columns=d) for df in [df1, df2, df3]]
一个简单的循环:
for df in [df1, df2, df3]:
df.rename(columns=d, inplace=True)
使用 map
:
df1, df2, df3 = list(map(lambda df: df.rename(columns=d), [df1, df2, df3]))
最后,恕我直言,带有 inplace=True
的简单循环是最优雅的。