【发布时间】:2016-03-11 08:04:01
【问题描述】:
这是我当前的数据框:
>>>df = {'most_exhibitions' : pd.Series(['USA (1) Netherlands (5)' ,
'United Kingdom (2)','China (3) India (5) Pakistan (8)','USA (11) India (4)'], index=['a', 'b', 'c','d']),
'name' : pd.Series(['Bob', 'Joe', 'Alex', 'Bill'], index=['a', 'b', 'c','d'])}
>>> df
name most_exhibitions
a Bob USA (1) India (5)
b Joe United Kingdom (2)
c Alex China (3) India (5) USA (8)
d Bill USA (11) India (4)
我正在尝试弄清楚如何拆分每个单元格,然后可能会从国家/地区创建一个新列并将相应的计数放在正确的行中。如果国家/地区已经是现有列,我只想将计数放在正确的行中。
所以,最终的数据框应该是这样的:
# name most_exhibitions USA United Kingdom China India
#a Bob USA (1), India (5) 1 5
#b Joe United Kingdom (2) 2
#c Alex China (3), India (5), USA (8) 8 3 5
#d Bill USA (11), India (4) 11 4
我想编写一个循环或函数来拆分数据,然后添加新列,但我不知道该怎么做。我最终通过一系列字典拆分和清理数据,现在我陷入了如何将最终字典变成自己的数据框的问题。我想,如果我能制作这个新的数据框,我就可以将它附加到旧的数据框上。我也认为我做的比它应该做的更难,并且对任何更优雅的解决方案感兴趣。
这是我到目前为止所做的:
>>>country_rank_df['country_split']
= indexed_rankdata['most_exhibitions'].str.split(",").astype(str)
from collections import defaultdict
total_dict = defaultdict(list)
dict2 = defaultdict(list)
dict3 = defaultdict(list)
dict4 = defaultdict(list)
dict5 = defaultdict(list)
dict6 = defaultdict(list)
for name, country_count in zip(head_df['name'], head_df['most_exhibitions']):
total_dict[name].append(country_count)
for key, value in total_dict.iteritems():
for line in value:
new_line = line.split('(')
dict2[key].append(new_line)
for key, list_outside in dict2.iteritems():
for list_inside in list_outside:
for value in list_inside:
new_line = value.split(',')
dict3[key].append(new_line)
for key, list_outside in dict3.iteritems():
for list_inside in list_outside:
for value in list_inside:
new_line = value.split(')')
dict4[key].append(new_line)
for key, list_outside in dict4.iteritems():
for list_inside in list_outside:
for value in list_inside:
new_line = value.strip()
new_line = value.lstrip()
dict5[key].append(new_line)
for key, list_outside in dict5.iteritems():
new_line = filter(None, list_outside)
dict6[key].append(new_line)
>>>dict6['Bob']
[['USA',
'1',
'India',
'5']]
【问题讨论】:
标签: python for-loop dictionary pandas