我的熊猫数据框为:-
categories
['business $ finance'\n 'business $currency']
['entertainment $movies' 'entertainment &music']
['sports& volleyball' 'sports& football'\n 'sports$ baseball']
...............
所有我想将这些放在方括号内的字符串转换为正确的列表格式。预期输出为:-
categories
['business $ finance','business $currency']
['entertainment $movies','entertainment &music']
['sports&volleyball','sports& football','sports$ baseball']
....................
到目前为止我尝试过的是:-
array_cat=[]
for i in df['categories']:
s=i[0].split()
array_cat.append(s)
df['categories'][0]
类似于:-
"['business finance#mergers & acquisitions' 'business#industries#telecom'\n 'diseases#kidney' 'gaming #offline #console#xbox'\n 'gaming #offline #playstation' 'lifestyle#shopping' 'movies#genres#drama'\n 'music#genres#hiphop/rap' 'personal finance#tools' 'technology#trending'\n 'theme#historicalsites']"
答案 0 :(得分:1)
对''
之间的所有值使用str.findall
:
df['categories'] = df['categories'].str.findall('\'(.*?)\'')
print (df)
categories
0 [business finance#mergers & acquisitions, busi...
1 [entertainment$movies, entertainment&music]
2 [sports&volleyball, sports&football, sports$ba...