2016-05-30 96 views
2

我有这样一本字典:怎样词典的词条有效地转换成数据帧

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 

这给了我所需的输出。

但是,我想知道是否有更高效的解决方案!

回答

4

这是我上线的方法:

df = pd.DataFrame([(k, s) for k, v in mydict.items() for s in v.split()], columns=['key_val','splitted_words']) 

如果我把它分解,这将是:

d=[(k, s) for k, v in mydict.items() for s in v.split()] 
df = pd.DataFrame(d, columns=['key_val','splitted_words']) 

输出:基于@瞿栋的

Out[41]: 
    key_val splitted_words 
0  A   some 
1  A   thing 
2  B   couple 
3  B    of 
4  B   words 
+1

不错,也许可以使用'.split()'而不是'.split('')' – jezrael

+0

@jezrael,谢谢你的建议!已编辑。 – 2342G456DI8

+0

非常棒!我现在喜欢并且稍后再接受,这取决于其他答案的质量。 – Cleb

4

想法和使用发电机功能的可读性一个工作示例:

#! /usr/bin/env python 
from __future__ import print_function 
import pandas as pd 

mydict = {'A': 'some thing', 
      'B': 'couple of words'} 


def splitting_gen(in_dict): 
    """Generator function to split in_dict items on space.""" 
    for k, v in in_dict.items(): 
     for s in v.split(): 
      yield k, s 

df = pd.DataFrame(splitting_gen(mydict), columns=['key_val', 'splitted_words']) 
print (df) 

# key_val splitted_words 
# 0  A   some 
# 1  A   thing 
# 2  B   couple 
# 3  B    of 
# 4  B   words 

# real 0m0.463s 
# user 0m0.387s 
# sys  0m0.057s 

但是这只能满足要求的优雅/可读性的效率。

如果你注意到它们的时间都是近似的。短暂超过500毫秒。所以人们可能会继续进一步剖析,以便在吃大文本时不会受到影响;-)

+0

好的方法,谢谢(upvoted)。 – Cleb