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

标签 python numpy pandas dataframe

我有两个列表:

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/

相关文章:

python - 为什么在微型 df 上使用 fast_executemany 会出现内存错误?

Python 拆分包含列表的字符串

python - 如何使用python通过gmail发送电子邮件?

python - 通过内省(introspection)行的每个元素来过滤 pandas 数据框

python - 为什么我的 numpy 构造忽略元组解构?

python - 如何访问 Numpy 数组中的元素

python - 如何将数据从numpy数组复制到另一个

python - 与外部 API 交互的基本电影数据库

python - Pandas:.loc[...] 的类似列表的索引

python - 组合 2 个数据帧以生成一个重复值文件