将Python列表解析为带有关键字的pandas.DataFrame

问题描述 投票:0回答:2

我有一个国家列表,应该变成一个数据框架。问题是每个国家和数据在列表中都是分开的单词。示例:

[
 'Viet',
 'Nam',
 '0',
 '12.3',
 '0',
 'Brunei',
 'Darussalam',
 '12',
 '1.1',
 '0',
 'Bosnia',
 'and',
 'Herzegovina',
 '2',
 '2.1',
 '0',
 'Not',
 'applicable',
 'Turkey',
 '4',
 '4.3',
 '0',
 'Only',
 'partial',
 'coverage'
...
]

如何将其转换为:[['越南','0','12.3','0'],[“文莱达鲁萨兰国”,“ 12”,“ 1.1”,...],...]或`pd.DataFrame:

             country  coef1  coef2  grade
0           Viet Nam      0   12.3      0
1  Brunei Darussalam     12    1.1      0

NOTE:某些国家/地区有一个单词,例如中国,法国,或者三个或更多单词,例如大韩民国。另外,有时在这一系列数字之后可能会有一个注释。

python list parsing data-conversion
2个回答
0
投票

尝试一下:

其中data_in是要解析的数据

data_in = [
    'Viet', 'Nam', '0', '12.3', '0', 'Brunei', 'Darussalam', '12', '1.1', '0'
]
data_out = []

for idx in range(0, len(data_in), 5): # considering that elements for each country always are 5 
    country = " ".join(data_in[idx:idx + 2])
    coef1 = data_in[idx + 2]
    coef2 = data_in[idx + 3]
    grade = data_in[idx + 4]
    data_out.append([country, coef1, coef2, grade])

print(data_out)

如果字段数一致,则输出

[['Viet Nam', '0', '12.3', '0'], ['Brunei Darussalam', '12', '1.1', '0']]

之后,您可以从此输出创建pandas.DataFrame

df = pd.DataFrame(data_out, columns=['country', 'coef1', 'coef1', 'grade'])
print(df)

哪个输出:

             country coef1 coef1 grade
0           Viet Nam     0  12.3     0
1  Brunei Darussalam    12   1.1     0

[如果不清楚,您可以发表评论,我会审查我的答案


0
投票

新列表是否始终为4列?如果是这样,则可以在开始处设置索引,根据列对列表进行切片,然后追加新列表。

import pandas as pd
mylist = ['Viet', 'Nam', '0','12.3',
          '0', 'Brunei', 'Darussalam', '12',
          '1.1']
index = 0
new_list = []
while index < len(mylist):
    indexslice = index + 4
    new_list.append(mylist[index:indexslice])
    index += 4
listDF = pd.DataFrame(new_list, columns=['Country','coef1','coef2','grade'])
print(listDF)

      0       1           2     3
0  Viet     Nam           0  12.3
1     0  Brunei  Darussalam    12
2   1.1    None        None  None

Process finished with exit code 0
© www.soinside.com 2019 - 2024. All rights reserved.