python - Pandas DataFrame 的多个列表

标签 python pandas list dataframe

我这里有三个列表

[1,2,3,4,5]

[5,4,6,7,2]

[1,2,4,5,6,7,8,9,0]

我想要这样的输出:

A     B    C
1     5    1
2     4    2
3     6    4
4     7    5
5     2    6
           7
           8
           9
           0

我尝试了一种语法,但它给了我这个错误 arrays must all be same length 另一个错误是 Length of values does not match length of index

有什么办法可以得到这种输出吗?

最佳答案

这不容易支持,但可以做到。 DataFrame.from_dict 将以“索引”为方向。假设您的列表是 ABC:

pd.DataFrame([A, B, C]).T

     0    1    2
0  1.0  5.0  1.0
1  2.0  4.0  2.0
2  3.0  6.0  4.0
3  4.0  7.0  5.0
4  5.0  2.0  6.0
5  NaN  NaN  7.0
6  NaN  NaN  8.0
7  NaN  NaN  9.0
8  NaN  NaN  0.0

另一种选择是使用 DataFrame.from_dict:

pd.DataFrame.from_dict({'A' : A, 'B' : B, 'C' : C}, orient='index').T

     A    B    C
0  1.0  5.0  1.0
1  2.0  4.0  2.0
2  3.0  6.0  4.0
3  4.0  7.0  5.0
4  5.0  2.0  6.0
5  NaN  NaN  7.0
6  NaN  NaN  8.0
7  NaN  NaN  9.0
8  NaN  NaN  0.0

使用 zip_longestDataFrame.from_records 的第三种解决方案:

from itertools import zip_longest
pd.DataFrame.from_records(zip_longest(A, B, C), columns=['A', 'B', 'C'])
# pd.DataFrame.from_records(list(zip_longest(A, B, C)), columns=['A', 'B', 'C'])

     A    B  C
0  1.0  5.0  1
1  2.0  4.0  2
2  3.0  6.0  4
3  4.0  7.0  5
4  5.0  2.0  6
5  NaN  NaN  7
6  NaN  NaN  8
7  NaN  NaN  9
8  NaN  NaN  0

关于python - Pandas DataFrame 的多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53849030/

相关文章:

java - 用另一个替换列表中的元素

javascript - 在 JavaScript 中将对象设置为键值(值是数组或列表)的 Immutable Map

python - 如何使用周期性值列拆分 pandas 数据框

python - 使用 Numpy 或 Pandas 根据字符计数对字符串进行矢量化分割

python - 将数字列表操作成列或单独的列表以在 Python 中绘图

python - 如何在 Django Admin 中更改 ForeignKey 显示文本?

python - 在 python 和 __repr__ 中动态创建类

python - 如何使用 REST api 将个人资料图像更新到 Twitter?

python - 在子进程中,某些命令有效,但 Mac 终端中的其他命令无效

python - 如何vlookup值并获取右侧的值