首页 > 解决方案 > 想将列表转换为以下示例的字符串

问题描述

我从一列得到一个结果集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

标签: pythonpython-3.x

解决方案


利用.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

推荐阅读