处理可变的列数数据框-Python [英] Handling Variable Number of Columns Dataframe - Python

查看:67
本文介绍了处理可变的列数数据框-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用熊猫将列表列表写入Excel工作表 列表如下:

I am trying to write a list of lists into an excel sheet using pandas the list looks like:

List_of Lists = [ [1,2,3,4],
                  [5,6,7,8],
                  [9,10,11,12],
                  ........,
                ]

主列表中这些列表的数量可能会增加到1000. 我也想将它们标记为colums1,colomns2,直到colums100 实例.在同一张纸上.熟悉熊猫的人可以帮助我吗? 因为对某些人来说这真的很容易吗?

The number of these lists inside the main list could go up to a 1000. I also want to label them like colums1, colomns2, until colums100 for instance. on the same sheets. can anyone familiar with pandas help me? as this could be really easy for some?

推荐答案

我相信您可以将列表传递到pd.DataFrame()中,并且将获得不存在的值的NaN.

I believe you can just pass the list into pd.DataFrame() and you will just get NaNs for the values that don't exist.

例如:

List_of_Lists = [[1,2,3,4],
                 [5,6,7],
                 [9,10],
                 [11]]
df = pd.DataFrame(List_of_Lists)
print(df)
    0     1    2    3
0   1   2.0  3.0  4.0
1   5   6.0  7.0  NaN
2   9  10.0  NaN  NaN
3  11   NaN  NaN  NaN

然后使用 pandas.DataFrame.add_prefix

df = df.add_prefix('Column')
print(df)
   Column0  Column1  Column2  Column3
0        1      2.0      3.0      4.0
1        5      6.0      7.0      NaN
2        9     10.0      NaN      NaN
3       11      NaN      NaN      NaN

现在我想您可能还希望每个列表都成为一列.在这种情况下,您需要转置List_of_Lists.

Now I guess there is the possibility that you also could want each list to be a column. In that case you need to transpose your List_of_Lists.

from itertools import zip_longest

df = pd.DataFrame(list(map(list, zip_longest(*List_of_Lists))))
print(df)
   0    1     2     3
0  1  5.0   9.0  11.0
1  2  6.0  10.0   NaN
2  3  7.0   NaN   NaN
3  4  NaN   NaN   NaN

这篇关于处理可变的列数数据框-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆