python - 如何从行中提取列名并将它们提升为标题?
问题描述
我正在阅读 csv,数据有点混乱。这是代码:
import pandas as pd
ocorrencias = pd.read_csv('data.csv', encoding="1252", header=None)
ocorrencias = ocorrencias.drop([0, 1, 2, 4, 10, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36], axis=1)
输出:
我想从行中删除列名并将它们提升到标题中,因此数据框将如下所示:
任何人都可以帮助我吗?
解决方案
您可以使用在单元格中split(': ')
仅保留部分:
df = df.apply(lambda x: x.str.split(': ', 1).str[1])
您还可以使用从任何行(即从第一行)split(': ')
获取列名.iloc[0]
df.columns = df.iloc[0].str.split(': ', 1).str[0]
最少的工作代码
首先,它必须在名称从单元格中删除之前获取标题。
我曾经random
生成随机值 - 但使用random.seed(0)
你应该得到与我的结果相同的值。
我使用1
insplit(': ', 1)
仅在第一次拆分它,因为如果您有文本值:
,有时可能会有更多。:
import pandas as pd
import random
random.seed(0) # to get the same random values in every test
df = pd.DataFrame([f'{col}: {random.randint(0,100)}'
for col in ['hello', 'world', 'of', 'python']]
for row in range(3))
print(df)
df.columns = df.iloc[0].str.split(': ', 1).str[0]
print(df)
df = df.apply(lambda x: x.str.split(': ', 1).str[1])
print(df)
结果:
0 1 2 3
0 hello: 49 world: 97 of: 53 python: 5
1 hello: 33 world: 65 of: 62 python: 51
2 hello: 100 world: 38 of: 61 python: 45
0 hello world of python
0 hello: 49 world: 97 of: 53 python: 5
1 hello: 33 world: 65 of: 62 python: 51
2 hello: 100 world: 38 of: 61 python: 45
0 hello world of python
0 49 97 53 5
1 33 65 62 51
2 100 38 61 45
推荐阅读
- c++ - 函数调用未被识别
- javascript - 使用 ejs 模板获取通过输入发布到同一页面的值
- sql - SQL IF 语句转换为文本
- android - Android:如何检查用户是否有活动订阅
- batch-file - CMD 使用 and 时删除空格(即“cmd /C ... && ...”)
- python - Python 3 + boto3 + s3:下载文件夹中的所有文件
- javascript - javascript/nativescript - 按 id 删除重复项但更新其他属性
- python - 将许多 .txt 文件转换为 csv 并将它们组合起来
- javascript - 如何用 Jest 模拟 ES6 单例类?
- machine-learning - r-squared 和调整后的 r-squared 之间的区别,有人可以帮我找到相同的好来源吗?