使用 python/pandas 中范围内的数字重命名列 [英] Renaming columns using numbers from a range in python/pandas
问题描述
我遇到了以下情况.我很确定我错过了一些简单的东西,但是我在这里和其他网站上尝试了很多建议,但没有找到我要找的东西.
我有一个包含许多随机命名列的数据框(由提供的 csv 文件提供).我想使用 range 函数中的数字重命名这些列.
由于我要重命名所有列,因此可以直接使用
df.columns = [str(x) for x in range(1,2000)]
但是,假设我可以通过 rename() 函数来实现吗?也许使用lambda?我尝试了许多不同的变体,但我遇到了各种各样的错误.我正在寻找语法来给我相当于
df.rename(columns= (str(x) for x in range(1,2000)))
其中 rename 根据给定的范围将名称按顺序分配给列.以上是行不通的.但是有没有办法让它发挥作用?
谢谢!
你可以通过一个 dict
来重命名 columns
kwarg:
df.rename(columns={x:y for x,y in zip(df.columns,range(0,len(df.columns)))})
这需要:
<前>>>> dfID1 ID2 POS1 POS2 TYPE TYPEVAL1 A 001 1 5 红色2 A 001 1 5 重量50KG3A 001 1 5 高度160CM4 A 002 6 19 未来 是5 A 002 6 19 目前没有6 B 001 26 34 颜色 蓝色7 B 001 26 34 重量85KG8 B 001 26 34 高120CM9 C 001 10 13 移动诺基亚10 C 001 10 13 平板 华硕并给你:
<前>>>> df.rename(columns={x:y for x,y in zip(df.columns,range(0,len(df.columns)))})0 1 2 3 4 51 A 001 1 5 红色2 A 001 1 5 重量50KG3A 001 1 5 高度160CM4 A 002 6 19 未来 是5 A 002 6 19 目前没有6 B 001 26 34 颜色 蓝色7 B 001 26 34 重量85KG8 B 001 26 34 高120CM9 C 001 10 13 移动诺基亚10 C 001 10 13 平板 华硕I'm stuck with the following situation. I'm pretty sure I'm missing something simple, but I tried a lot of suggestions here and at other sites, and haven't found what I'm looking for.
I have a dataframe with a lot of randomly named columns (courtesy of provided csv file). I would like to rename these columns using digits from the range function.
Since I'm renaming all columns, I could do it directly using
df.columns = [str(x) for x in range(1,2000)]
However, hypothetically, could I do it through the rename() function? Maybe using a lambda? I have tried many different variations, but I'm getting all sorts of errors. I'm looking for the syntax to give me the equivalent of
df.rename(columns= (str(x) for x in range(1,2000)))
where rename assigns the name to the columns sequentially based on the given range. The above does't work. But is there a way to make it work?
Thank you!
You can pass a dict
to rename's columns
kwarg:
df.rename(columns={x:y for x,y in zip(df.columns,range(0,len(df.columns)))})
That will take:
>>> df ID1 ID2 POS1 POS2 TYPE TYPEVAL 1 A 001 1 5 COLOR RED 2 A 001 1 5 WEIGHT 50KG 3 A 001 1 5 HEIGHT 160CM 4 A 002 6 19 FUTURE YES 5 A 002 6 19 PRESENT NO 6 B 001 26 34 COLOUR BLUE 7 B 001 26 34 WEIGHT 85KG 8 B 001 26 34 HEIGHT 120CM 9 C 001 10 13 MOBILE NOKIA 10 C 001 10 13 TABLET ASUS
And give you:
>>> df.rename(columns={x:y for x,y in zip(df.columns,range(0,len(df.columns)))}) 0 1 2 3 4 5 1 A 001 1 5 COLOR RED 2 A 001 1 5 WEIGHT 50KG 3 A 001 1 5 HEIGHT 160CM 4 A 002 6 19 FUTURE YES 5 A 002 6 19 PRESENT NO 6 B 001 26 34 COLOUR BLUE 7 B 001 26 34 WEIGHT 85KG 8 B 001 26 34 HEIGHT 120CM 9 C 001 10 13 MOBILE NOKIA 10 C 001 10 13 TABLET ASUS
这篇关于使用 python/pandas 中范围内的数字重命名列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!