【发布时间】:2016-09-28 04:31:33
【问题描述】:
我有一本这样的字典:
mydict = {'A': 'some thing',
'B': 'couple of words'}
所有值都是由空格分隔的字符串。我的目标是将其转换为如下所示的数据框:
key_val splitted_words
0 A some
1 A thing
2 B couple
3 B of
4 B words
所以我想拆分字符串,然后将关联的键和这些单词添加到数据框的一行中。
快速实现可能如下所示:
import pandas as pd
mydict = {'A': 'some thing',
'B': 'couple of words'}
all_words = " ".join(mydict.values()).split()
df = pd.DataFrame(columns=['key_val', 'splitted_words'], index=range(len(all_words)))
indi = 0
for item in mydict.items():
words = item[1].split()
for word in words:
df.iloc[indi]['key_val'] = item[0]
df.iloc[indi]['splitted_words'] = word
indi += 1
这给了我想要的输出。
但是,我想知道是否有更有效的解决方案!?
【问题讨论】:
标签: python performance dictionary pandas