我这里有三个列表
[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
将以“索引”为方向。假设您的列表是 A
、B
和 C
:
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_longest
和 DataFrame.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/