pandas - 从列表创建多列 pandas 数据框

标签 pandas list multiple-columns

我不知道如何从列表创建 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/

相关文章:

r - 使用 purrr :map 将向量映射到键值列表

php - 一个查询插入多行多列

scala - 无 :List[Int] as parameter

python - 如何使用多个条件过滤 Python 列表?

python - 绘制所有边都清晰可见的网络图

python - 当范围未知时,Pandas 按值范围分组

css - 使用 CSS 列并确保直接子项的内容不换行

html - CSS3 : Multi Column System with Titles

python - 如何通过任意长度的两列列表对 pandas 数据框进行子集化

python - TreeMap 路径中二进制字符串的表示