[英]How to concatenate rows of a Pandas series in Python
我有一個包含許多行的 Python pandas 系列,這些行包含一個單詞列表,例如:
25 [estimated, million, people, lived, vulnerable...
176 [cent, vulnerable]
7 [create, sound, policy, frameworks, poor, vuln...
299 [create, sound, policy, frameworks, cent, vuln...
283 [missing, international, levels, based, estima...
...
63 [create, sound, policy, frameworks, world, pop...
259 [build, world, population, still, lived]
193 [create, sound, policy, frameworks, every, sta...
284 [cent, situation, remains, particularly, alarm...
43 [based, less, cent, share, property, inheritan...
Name: clean_text, Length: 300, dtype: object
如何將所有行的單詞連接到一個列表中? 我試過了:
nameofmyfile.str.cat(sep=', ')
但我得到一個錯誤:
TypeError:不能使用帶有推斷 dtype 'mixed' 值的.str.cat。
這是一個hacky方式。
# step 1: Convert to a list
our_list = df["series"].tolist()
# step 2: Make a new empty list and build it up
new_list = []
for words in our_list:
new_list += words
@Alexis 給出的解決方案很好,但我總是反對使用循環並投票支持矢量化。 我創建了非常相似的系列,就像問題中給出的那樣,即:
>>> a
foo [hi, hello, hey]
bar [I, me, myself]
dtype: object
現在使用 numpy 中的連接方法, foo, bar
的列表將連接在一起形成一個元素數組:
>>> import numpy as np
>>> np.concatenate(a.values)
array(['hi', 'hello', 'hey', 'I', 'me', 'myself'], dtype='<U6')
Now I dont think there should be any problem with a numpy array returned, still if you want output as list you can use inbuilt list()
method or numpy.ndarray's .tolist()
method to get output as a list.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.