首页 > 解决方案 > 通过python应用循环更改列名和拆分文本

问题描述

输入文件:输入图像

import pandas as pd
df = pd.read_excel("C:/Users/Desktop/Replace.xlsx",header=None)
df.shape[1]
df['Ind 0'] = df['Col 0'].str[1:]
df['Ind 1'] = df['Col 1'].str[1:]
df['Ind 2'] = df['Col 2'].str[1:]
df.to_excel("C:/Users/Desktop/Replace.xlsx", index=False)

所需输出:输出图像

我从上面的代码中得到这个输出。但是,我需要这个任务的循环(分配新的列名和对列值的一些切片操作)。这样每当列数值发生变化时。如前所述,它将自动处理并提供所需的输出。

标签: pythonpython-3.xpandasdataframe

解决方案


尝试这个

import pandas as pd
d = {'Col 1': ['1A', '1B', '1C', '1D'], 'Col 2': ['2A', '2B', '2C', '2D'], 'Col 3': ['3A', '3B', '3C', '3D']}
df = pd.DataFrame(d)
df = df.replace(regex=r'[0-9]', value= '')
df.columns = ['Ind 1', 'Ind 2', 'Ind 3']
print(df)

输出:

  Ind 1 Ind 2 Ind 3
0     A     A     A
1     B     B     B
2     C     C     C
3     D     D     D

推荐阅读