首页 > 解决方案 > 如何从行中提取列名并将它们提升为标题?

问题描述

我正在阅读 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)

输出:

输出

我想从行中删除列名并将它们提升到标题中,因此数据框将如下所示:

后

任何人都可以帮助我吗?

标签: pythonpandas

解决方案


您可以使用在单元格中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)你应该得到与我的结果相同的值。

我使用1insplit(': ', 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

推荐阅读