想要将列表转换为字符串,例如以下示例

时间:2019-05-21 10:05:02

标签: python python-3.x

我从df['Test'].head()列中得到一个结果集:

0    [fed, official, say, weak, data, caused, weather, slow, taper]     
1    [fed, 's, charles, plosser, see, high, bar, change, pace, tapering]

我想将其转换如下,并存储在与

相同的列中
fed official say weak data caused weather slow taper
fed 's Charles plosser see high bar change pace tapering

4 个答案:

答案 0 :(得分:2)

使用.apply(" ".join)

例如:

import pandas  as pd

df = pd.DataFrame({'Test': [['fed', 'official', 'say', 'weak', 'data', 'caused', 'weather', 'slow', 'taper'],
                            ['fed', "'s", 'charles', 'plosser', 'see', 'high', 'bar', 'change', 'pace', 'tapering']
                           ]
                })
print(df["Test"].apply(" ".join))

输出:

0    fed official say weak data caused weather slow...
1    fed 's charles plosser see high bar change pac...
Name: Test, dtype: object

答案 1 :(得分:1)

由于您的列表格式不正确,

首先我转换为单词列表,然后转换为字符串。

代码:

>>> import pandas as pd

>>> df = pd.DataFrame({'Test': ["[fed, official, say, weak, data, caused, weather, slow, taper]",
                            "[fed, 's, charles, plosser, see, high, bar, change, pace, tapering]"
                           ]
                })

>>> df['Test']=df['Test'].str[1:-1].str.split(', ').apply(' '.join)

输出:

>>> df
                                                Test
0  fed official say weak data caused weather slow...
1  fed 's charles plosser see high bar change pac...

答案 2 :(得分:0)

尝试:

for index, row in df.iterrows() : 
  s = ''
  for i in row['Test'] : 
    s = s + i
  df['Test'][index] = s

答案 3 :(得分:0)

谢谢大家的帮助。

df ['Test']。apply(lambda x:“” .join([x.split()中单词的Word(word).lemmatize()))

它适用于上述情况。