Pandas列到字符串

时间:2017-09-25 18:54:52

标签: python pandas dataframe

将pandas列转换为一个串联字符串的最快方法是什么?

例如,如果df['col1']包含以下内容:

col1
word1
word2
word3

返回'word1 word2 word3'的理想方式是什么?

1 个答案:

答案 0 :(得分: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=' ')
  • 快得多