要将下面的examp列表转换为字符串吗

2024-05-18 07:53:13 发布

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

我从一列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

Tags: databarchangesayweatherslowofficialhigh
3条回答

试试这个:

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

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

因为你的单子格式不合适

首先我转换成单词列表,然后转换成字符串。你知道吗

代码:

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

相关问题 更多 >