2017-09-25 30 views
0

pandas列を1つの連結文字列に変換する最も速い方法は何ですか?例えばPandas列から文字列へ

df['col1']は以下が含まれる場合、:

col1 
word1 
word2 
word3 

'word1 word2 word3'を返すための理想的な方法は何ですか?

答えて

3

オプション1]使用str.cat

In [3761]: df.col1.str.cat(sep=' ') 
Out[3761]: 'word1 word2 word3' 

オプション2]使用join

In [3763]: ' '.join(df.col1) 
Out[3763]: 'word1 word2 word3' 

代わりに高速この場合であるlistを使用します。

In [3794]: ' '.join(df.col1.values.tolist()) 
Out[3794]: 'word1 word2 word3' 

In [3795]: df.col1.values.tolist() 
Out[3795]: ['word1', 'word2', 'word3'] 

タイミング

中型

In [3769]: df.shape 
Out[3769]: (30000, 1) 

In [3770]: %timeit df.col1.str.cat(sep=' ') 
100 loops, best of 3: 2.71 ms per loop 

In [3771]: %timeit ' '.join(df.col1) 
1000 loops, best of 3: 796 µs per loop 

In [3788]: %timeit ' '.join(df.col1.values.tolist()) 
1000 loops, best of 3: 492 µs per loop 

大型

In [3774]: df.shape 
Out[3774]: (300000, 1) 

In [3775]: %timeit df.col1.str.cat(sep=' ') 
10 loops, best of 3: 29.7 ms per loop 

In [3776]: %timeit ' '.join(df.col1) 
100 loops, best of 3: 9.22 ms per loop 

In [3791]: %timeit ' '.join(df.col1.values.tolist()) 
100 loops, best of 3: 6.69 ms per loop 

  • ' '.join(df.col1.values.tolist())が、これは素晴らしい作品、df.col1.str.cat(sep=' ')
+0

多くの感謝よりもはるかに高速です。 – Seano314

関連する問題