gpt4 book ai didi

python - 在数据帧 : as rows and columns 中加入列表的两种方法

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:54 25 4
gpt4 key购买 nike

我有两个列表:

l1 = ['0a',22,44]
l2 = ['0b',25,55,66]

现在我加入它们,使每个列表成为数据框的一列:

import pandas as p
df1 = p.DataFrame(zip(l1,l2))
df1

我收到了 3 行 2 列的数据框(l2 的值 66 被遗漏了)。它看起来与 ndarray 的定义相同,它说:“如果 ndarray 被传递到数据帧中,所有列必须具有相同的行数” .但我不使用 ndarray!

但是,如果我将列表作为数据框的行加入,则 Python 保存 66:

df2 = p.DataFrame([l1,l2])

有没有办法将列表作为列传递到数据框中,同时将列表的所有值保存在数据框中

最佳答案

函数 zip 返回长度被截断为最短参数序列长度的列表。所以结果将是:

In [1]: zip(l1,l2)
Out[1]: [('0a', '0b'), (22, 25), (44, 55)]

要保存值 66 使用 izip_longest来自 itertools:

In [3]: p.DataFrame(list(itertools.izip_longest(l1, l2)))
Out[3]:
0 1
0 0a 0b
1 22 25
2 44 55
3 None 66

或者您可以将 mapNone 一起使用。 (但是 map 在 Python 3.x 中发生了变化,因此它只适用于 Python 2.x):

In [4]: p.DataFrame(map(None, l1, l2))
Out[4]:
0 1
0 0a 0b
1 22 25
2 44 55
3 None 66

关于python - 在数据帧 : as rows and columns 中加入列表的两种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32443708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com