[英]Convert string from pandas dataframe into a list - python
I have a pandas dataframe which has a column structured as well:我有一个 pandas dataframe 它也有一个列结构:
sequences
-------------
[(1838, 2038)]
[]
[]
[(809, 1090)]
I'need to loop row by row, so I structured the loop as well:我需要逐行循环,所以我也构建了循环:
for index, row in df.iterrows():
true_anom_seq = json.loads(row['sequences'])
What I wanna do is create a nested loop like [[1838, 2038], [], [], [809, 1090]]
so I can iterate through it.我想做的是创建一个像
[[1838, 2038], [], [], [809, 1090]]
这样的嵌套循环,这样我就可以遍历它。 The problem is that the code I wrote gives me the error:问题是我写的代码给了我错误:
JSONDecodeError: Expecting value: line 1 column 2 (char 1)
I also tried to print row['sequences'][0]
and it gives me [
, so it is reading it as a string.我还尝试打印
row['sequences'][0]
并且它给了我[
,所以它将它作为字符串读取。
How can I convert this string to a list?如何将此字符串转换为列表?
Use ast.literal_eval to convert strings to list/dict/...:使用 ast.literal_eval 将字符串转换为 list/dict/...:
from ast import literal_eval
>>> literal_eval('[1,2,3]')
[1,2,3]
import pandas as pd
import re
col = {'index': [1,2,3,4], 'sequence':['[(1838, 2038)]', '[]', '[]', '[(809, 1090)]']}
new_sequence = []
new_df = pd.DataFrame(col)
for index, row in new_df.iterrows():
one_item = []
true_anom_seq = re.findall(r'\d+', row['sequence'])
for match in true_anom_seq:
one_item.append(match)
new_sequence.append(one_item)
print(new_sequence)
No need to iterate through the dataframe itself nor use regex.无需遍历 dataframe 本身,也无需使用正则表达式。 Just apply the literal_eval function to each row in the
sequence
column and wrap it as a list:只需将 literal_eval function 应用于
sequence
列中的每一行并将其包装为列表:
from ast import literal_eval
import pandas as pd
col = {'index': [1,2,3,4], 'sequence':['[(1838, 2038)]', '[]', '[]', '[(809, 1090)]']}
new_sequence = []
new_df = pd.DataFrame(col)
list(new_df.sequence.apply(literal_eval))
[[(1838, 2038)], [], [], [(809, 1090)]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.