使用str+numb用数字重命名特定列

2024-06-23 19:34:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我原来有r个csv文件

我创建了一个包含9列的数据帧,其中r列的标题是数字

我想只针对他们和改变他们的名字为['Apple']+范围(len(files))

示例: 我有3个csv文件

“我的数据帧”中当前的3个目标列是:

            0       1       2  
0       444.0   286.0   657.0  
1      2103.0  2317.0  2577.0  
2       157.0   200.0   161.0  
3      4000.0  3363.0  4986.0  
4      1042.0   541.0   872.0  
5      1607.0  1294.0  3305.0

我想:

       Apple1  Apple2    Apple3  
0       444.0   286.0   657.0  
1      2103.0  2317.0  2577.0  
2       157.0   200.0   161.0  
3      4000.0  3363.0  4986.0  
4      1042.0   541.0   872.0  
5      1607.0  1294.0  3305.0

谢谢


Tags: 文件csv数据标题示例apple目标len
3条回答

IIUC,您可以初始化itertools.count对象并重置列表中的列

from itertools import count

cnt = count(1)
df.columns = ['Apple{}'.format(next(cnt)) if 
       str(x).isdigit() else x for x in df.columns]

如果数字不是连续的,但您希望用连续的后缀重命名它们,这也会非常有效:

print(df)
       1   Col1       5    Col2     500
0  1240.0  552.0  1238.0    52.0  1370.0
1   633.0  435.0   177.0  2201.0   185.0
2  1518.0  936.0   385.0   288.0   427.0
3   212.0  660.0   320.0   438.0  1403.0
4    15.0  556.0   501.0  1259.0  1298.0
5   177.0  718.0  1420.0   833.0   984.0

cnt = count(1)
df.columns = ['Apple{}'.format(next(cnt)) if 
         str(x).isdigit() else x for x in df.columns]

print(df)
   Apple1   Col1  Apple2    Col2  Apple3
0  1240.0  552.0  1238.0    52.0  1370.0
1   633.0  435.0   177.0  2201.0   185.0
2  1518.0  936.0   385.0   288.0   427.0
3   212.0  660.0   320.0   438.0  1403.0
4    15.0  556.0   501.0  1259.0  1298.0
5   177.0  718.0  1420.0   833.0   984.0

可以使用“重命名U轴”:

df.rename_axis(lambda x: 'Apple{}'.format(int(x)+1) if str(x).isdigit() else x, axis="columns")
Out[9]: 
   Apple1  Apple2  Apple3
0   444.0   286.0   657.0
1  2103.0  2317.0  2577.0
2   157.0   200.0   161.0
3  4000.0  3363.0  4986.0
4  1042.0   541.0   872.0
5  1607.0  1294.0  3305.0

相关问题 更多 >

    热门问题