如何根据特定于列表的标准从列表创建数据帧

2024-04-19 22:00:58 发布

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

我有以下清单:

['1',
 'William Dunn Moseley',
 'June 25, 1845–October 1, 1849(term limited)',
 'Democratic',
 '1845',
 'Office did not exist',
 '2',
 'Thomas Brown',
 'October 1, 1849–October 3, 1853(term limited)',
 'Whig',
 '1849',
 '3',
 'James E. Broome',
 'October 3, 1853–October 5, 1857(term limited)',
 'Democratic',
 '1853',
]

列表中的每个数字对应于我要生成的数据集中的一行。因此,从这个列表中,我想生成一个如下所示的数据集:

Number         Name                            Term                              Party       Election       Office
1      'William Dunn Moseley' 'June 25, 1845–October 1, 1849(term limited)'    Democratic     1845    'Office did not exist'
2          'Thomas Brown'     'October 1, 1849–October 3, 1853(term limited)'    'Whig'      '1849'    NA
3         'James E. Broome'   'October 3, 1853–October 5, 1857(term limited)'  'Democratic'  '1853'    NA

有没有一种简单的方法可以根据列表中的某些值(如行号)或在这些值之间将列表翻转到数据框中?你知道吗

如果您能提供任何帮助,我们将不胜感激!非常感谢。你知道吗


Tags: 数据列表notthomasexistofficewilliamterm
3条回答

很难做到100%的精确,因为你的数据是不规则的,但这里有一些东西。你知道吗

import numpy as np
import pandas as pd

number_of_presidents = 3

presidents = np.array(['1',
 'William Dunn Moseley', 'June 25, 1845–October 1, 1849(term limited)',
 'Democratic', '1845',  'Office did not exist',  '2', 'Thomas Brown',
 'October 1, 1849–October 3, 1853(term limited)', 'Whig', '1849',
 '3', 'James E. Broome', 'October 3, 1853–October 5, 1857(term limited)',
 'Democratic', '1853'])

indexes = []

for i in range(1, number_of_presidents + 1):
    indexes.append(np.where(presidents == str(i))[0][0])

df = pd.DataFrame(np.split(presidents, indexes)[1:]).iloc[:, 1:]

print(df)
    1  ...                     5

0 William Dunn Moseley ... Office did not exist

1 Thomas Brown ... None

2 James E. Broome ... None

[3 rows x 5 columns]

您可以通过在数组中循环来实现它,将i的值增加您拥有的列数,并将数据保存在字典中,例如: enter image description here

如果最后两位总统没有“办公室不存在”,那就不重要了。你不需要知道有多少位总统。;D

当遇到索引时,可以简单地循环并将它们分成行

temp = []
output = []
idx = 0

for row in a:
    if row.isnumeric() and int(row) == idx+1:
        output.append(temp)
        temp = []
        idx += 1
        continue
    temp.append(row)

output.append(temp)
df = pandas.DataFrame(output[1:], columns=column_names)

这会给你想要的。但是你必须给列名贴上标签。你知道吗

相关问题 更多 >