如何使用pandas将列表转换为str?

2024-10-02 18:26:18 发布

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

type(df['Soft_skills'][0])
>>>str

我需要像这样输出

df['Soft_skills'][0] = Management,Decision Making

第二排呢

df['Soft_skills'][1] = None

我不知道如何删除"并将其转换为str格式

>>> df['Soft_skills']
0                       ["Management", "Decision Making"]
1                                                      []
2                                          ["Management"]
3                                                      []
4       ["Governance", "Management", "Leadership", "Te...
                              ...
1229                                                   []
1230                                                   []
1231                                                   []
1232                   ["Agenda (Meeting)", "Governance"]
1233                                                   []
Name: Soft_skills, Length: 1234, dtype: object

在某些情况下,数据是无效的 The syllabus for this course will cover the following:, \n, *, The nature and purpose of cost and management accounting, \n, *, Source documents and coding, \n, *, Cost classification and measuring, \n, *, Recording costs, \n, *, Spreadsheets 我用

d = {
'Not Mentioned':'',
"\r\n": "\n",
"\r": "\n",
'\u00a0':' ',
': \n, *,  ':'\n * ',
' \n,':'\n',
}
df=df.replace(d.keys(),d.values(),regex=True)

但是没有什么可以替代我在尝试时遇到的问题是什么?我遗漏了什么? 我也用过这个

df['Course_content'] = df['Course_content']\
    .str.replace('Not Mentioned','')\
    .str.replace("\r\n", "\n")\
    .str.replace("\r", "\n")\
    .str.replace('\u00a0',' ')\
    .str.replace(', \n, *,  ','\n * ')\
    .str.replace(' \n,','\n')

但这对我来说也不管用


Tags: andthedfnotmanagementreplaceskillssoft
1条回答
网友
1楼 · 发布于 2024-10-02 18:26:18

通过strip()replace()尝试:

df['Soft_skills']=(df['Soft_skills'].str.strip("[]")
              .str.replace("'",'')
              .replace('',float('nan'),regex=True))

更新:

首先创建了一个字典:

d={
    'Â':'',
    '’':"'",
    '“':'"',
    '–':'-',
    'â€':'"'
}

最后使用replace()方法:

df=df.replace(d.keys(),d.values(),regex=True)

Source:我从this answer创建了字典,这与php相同,但存在相同的编码问题

相关问题 更多 >