python - 通过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)
所需输出:输出图像
我从上面的代码中得到这个输出。但是,我需要这个任务的循环(分配新的列名和对列值的一些切片操作)。这样每当列数值发生变化时。如前所述,它将自动处理并提供所需的输出。
解决方案
尝试这个
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
推荐阅读
- c - 动态设置 MAX_STRINGS
- java - 使用 Selenium 网格和 jenkins 通过 Web 界面上传带有空手道测试的文件
- c++ - 三元运算符的意外结果
- mysql - 在 SQL 中选择不同的对
- charts - 如何获取Power BI日期切片器中选择的最小日期的对应价格
- python - Python xgb:ValueError:“feature_names 不匹配”
- php - php calendar - 从星期一开始日历
- minikube - 在本地网络服务器上安装 Eclipse Che 7.0 并从不同的机器访问
- java - 如何在java中删除链接列表的最后一个节点?
- javafx - 指定的文件夹不包含 Java 平台