我不知道如何从列表创建 pandas 数据框(多列)。有些行的开头包含字符“">”。我希望它们成为列标题。每个标题后的行数不相同。
我的列表:
>header
a
b
>header2
c
d
e
f
>header3
g
h
i
我想创建的数据框:
>header1 >header2 >header3
a c g
b d h
e i
f
最佳答案
只需迭代各行并用“>”匹配标题即可。但挑战是从大小不等的列表字典中创建 df。
# The given list
lines = [">header", "a", "b", ">header2", "c", "d", "e", "f", ">header3", "g", "h", "i"]
# Iterate through the lines and create a sublist for each header
data = {}
column = ''
for line in lines:
if line.startswith('>'):
column = line
data[column] = []
continue
data[column].append(line)
# Create the DataFrame
df = pd.DataFrame.from_dict(data,orient='index').T
输出:
>header >header2 >header3
0 a c g
1 b d h
2 None e i
3 None f None
关于pandas - 从列表创建多列 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75112428/