python - 处理可变列数数据框 - Python

标签 python pandas dataframe xlw

我正在尝试使用 Pandas 将列表列表写入 Excel 工作表 该列表如下所示:

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

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。

例如:

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

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 - 处理可变列数数据框 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43478867/

相关文章:

python - Spotipy:如何从播放列表中读取超过 100 首轨道

python - 在python中计算每年前10名的平均值(groupby,nlargest)

python - django admin static 服务于错误的 url

python - 对多个 Excel 电子表格重复 df.reindex

python - 在 Pandas 的一列中切片字符串

python - 从 Python 数据框中的整数中检索工作日名称

r - 根据向量中*不*的列选择 R 数据框中的列

python - 检查 pandas df.iterrows() 中的最后一行是否

python - 无法从 scrapy 项目中将数据插入到 sql 表中

python - 如何使用准备好的语句使用 Python/Django 在 SQlite 中插入多条记录?