2017-09-25 165 views
0

將熊貓列轉換爲一個串聯字符串的最快方法是什麼?將熊貓列轉換爲字符串

例如,如果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