这将比应用解决方案(和循环解决方案)更快
仅供参考:(这是0.13)。在0.12中,您需要首先创建Type列。在In [36]: data.loc[data.Lang.str.match(pat[0]),'Type'] = 'B'
In [37]: data.loc[data.Lang.str.match(pat[1]),'Type'] = 'A'
In [38]: data
Out[38]:
Lang Type
0 Python B
1 Cython NaN
2 Scipy A
3 Numpy NaN
4 Pandas B
[5 rows x 2 columns]
In [39]: data.fillna('')
Out[39]:
Lang Type
0 Python B
1 Cython
2 Scipy A
3 Numpy
4 Pandas B
[5 rows x 2 columns]
以下是一些时间安排:
^{pr2}$
你最初的想法
^{3}$
直接索引In [42]: %timeit f2(bigdata)
100 loops, best of 3: 17.3 ms per loop
应用In [43]: %timeit f1(bigdata)
10 loops, best of 3: 21.8 ms per loop
这是另一种更通用的方法,它速度更快,prob更有用
如果你想的话,你可以在groupby中组合模式。在In [107]: pats
Out[107]: {'A': '^P\\w', 'B': '^S\\w'}
In [108]: concat([df,DataFrame(dict([ (c,Series(c,index=df.index)[df.Lang.str.match(p)].reindex(df.index)) for c,p in pats.items() ]))],axis=1)
Out[108]:
Lang A B
0 Python A NaN
1 Cython NaN NaN
2 Scipy NaN B
3 Numpy NaN NaN
4 Pandas A NaN
5 Python A NaN
6 Cython NaN NaN
45 Python A NaN
46 Cython NaN NaN
47 Scipy NaN B
48 Numpy NaN NaN
49 Pandas A NaN
50 Python A NaN
51 Cython NaN NaN
52 Scipy NaN B
53 Numpy NaN NaN
54 Pandas A NaN
55 Python A NaN
56 Cython NaN NaN
57 Scipy NaN B
58 Numpy NaN NaN
59 Pandas A NaN
... ... ...
[10000 rows x 3 columns]
In [106]: %timeit concat([df,DataFrame(dict([ (c,Series(c,index=df.index)[df.Lang.str.match(p)].reindex(df.index)) for c,p in pats.items() ]))],axis=1)
100 loops, best of 3: 15.5 ms per loop
这个框架为每个模式附加一个序列,使字母处于正确的位置(否则为NaN)。在
创造一系列的字母Series(c,index=df.index)
从中选择匹配项Series(c,index=df.index)[df.Lang.str.match(p)]
重新编制索引时,将NaN放入索引中不存在的值Series(c,index=df.index)[df.Lang.str.match(p)].reindex(df.index))