加入一个列表中的元素

2024-10-01 05:03:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据帧列,这是一个系列。列包含字符串列表中的元素。但是,此列基本上是postgresql的数组,因此每个元素都是一个列表,但类似于:

<type 'list'>

以下是本专栏(系列)的前两个元素的外观

0    [UMIN Clinical Trial Registry [Website Last up...
1    [Disposition of Patients \n\nSTARTED; Tetracai...
Name: notes, dtype: object

当我执行列[0]时,我得到:

['UMIN Clinical Trial Registry [Website Last updated date: May 26, 2011] \n\nRecruitment status: Not yet recruiting \n\nDate of protocol fixation: 02/01/2011 \n\nAnticipated trial start date: 07/01/2011 \n\nName of primary sponsor: The Second Department of Internal Medicine Tokyo Medical University \n\nSource of funding: OMRON Health Care corporation \n\nhttps://upload.umin.ac.jp/cgi-open-bin/ctr/ctr.cgi?function=brows&action=brows&type=summary&recptno=R000006682&language=E', 'The projected start date 07/01/2011 was removed because that date passed without evidence of trial start.\n\nhttps://upload.umin.ac.jp/cgi-open-bin/ctr/ctr.cgi?function=brows&action=brows&type=summary&recptno=R000006682&language=E']

如果您看到此列的每个元素都是一个字符串列表。我想得到最后一列,其中每个元素不是一个字符串列表,而是应该组合列表中的所有字符串,并作为字符串给出。你知道吗

问题是list元素本身是一个字符串,因为它是使用array\u agg创建的。所以我不能使用“.join(column[0])作为iterable。给出一个错误,列[0]不是列表,而是“list”类型

如何克服这个问题?你知道吗

编辑:

 If I do this: 

for x in column: 
   s=" ".join(x) 
   docs.append(s) 
   break 

它起作用了。但是如果我不想用break语句来完成所有的操作,它会抛出一个错误:

for x in column:
   s=" ".join(x) 
   docs.append(s)

错误:

<ipython-input-154-556942a06d81> in <module>() 1 for x in trials_notes.notes: ----> 2 s=" ".join(x) 3 docs.append(s) 4 TypeError: can only join an iterable –

Tags: of字符串in元素列表datetypecolumn
1条回答
网友
1楼 · 发布于 2024-10-01 05:03:53

可以使用^{}并将要连接的分隔符作为参数。示例-

新列=列.str.join('')

演示-

In [3]: import pandas as pd

In [4]: column = pd.Series([['blah1'],['blah2'],['blah123']],name='blah')

In [5]: column.str.join(' ')
Out[5]:
0      blah1
1      blah2
2    blah123
Name: blah, dtype: object

In [7]: type(column[0])
Out[7]: list

相关问题 更多 >