我有一个 pandas 数据框,它也有一个列结构:
sequences
-------------
[(1838, 2038)]
[]
[]
[(809, 1090)]
我需要逐行循环,所以我也构建了循环:
for index, row in df.iterrows():
true_anom_seq = json.loads(row['sequences'])
我想要做的是创建一个像 [[1838, 2038], [], [], [809, 1090]]
这样的嵌套循环,这样我就可以迭代它。问题是我写的代码给了我错误:
JSONDecodeError: Expecting value: line 1 column 2 (char 1)
我还尝试打印 row['sequences'][0]
,它给了我 [
,因此它将它作为字符串读取。
如何将此字符串转换为列表?
最佳答案
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)
关于python - 将字符串从 pandas 数据帧转换为列表 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70712730/