这是我的数据框
在 Cover Design 列中,很少有以“- undefined”结尾的值,我想将其删除。所以,我使用 split 函数来删除
test[['ttt']] = test['Cover Design'].str.split(' - undefined')
这就是我得到的
但新列中的值是列表类型如何将其转换为字符串?
请您参考如下方法:
您的解决方案应该更改为 str[0],以便在 split 之后选择列表的第一个值:
test['ttt'] = test['Cover Design'].str.split(' - undefined').str[0]
另一个解决方案是使用 Series.str.replace :
test['ttt'] = test['Cover Design'].str.replace(' - undefined', '')
如果需要通过正则表达式指定字符串结束 $:
test['ttt'] = test['Cover Design'].str.replace(' - undefined$', '')
错误的解决方案是使用 strip,因为它从字符串的结尾和开头删除 - undefined 中的所有值,不要使用它:
test['ttt'] = test['Cover Design'].str.strip(' - undefined')
