【问题标题】:Structure a list of lists as columns and rows for csv/Excel将列表列表构造为 csv/Excel 的列和行
【发布时间】:2018-08-25 09:34:56
【问题描述】:

我有这个 python3 代码,其中包含我需要以某种方式为 Excel 构建的列表列表。这是我所拥有的:

>>> pprint(avrop_categories[0:3])

[['Name1', ['MainCategory1', 'SubCategory1', ('Item1', 1.0)]],

['Name2',
['MainCategory2', 'Subcategory2', ('Item2', 1.0)],
['MainCategory2', 'Subcategory3', ('Item3', 1.0)],
['MainCategory2', 'Subcategory4', ('Item4', 1.0)],
['MainCategory3', 'Subcategory5', ('Item5', 1.0)],
['MainCategory4', 'Subcategory6', ('Item6', 1.0)],
['MainCategory5', 'Subcategory7', ('Item7', 1.0)],
['MainCategory5', 'Subcategory8', ('Item8', 1.0)],
['MainCategory5', 'Subcategory9', ('Item9', 1.0)]],

['Name3',
['MainCategory3', 'Subcategory10', ('Item10', 1.0)], #<-note MainCategory3 again.
['MainCategory6', 'Subcategory11', ('Item11', 1.0)]]]

我需要解决这个问题。 IE。行中的名称,列中的 MainCategories 和计入其 MainCategories 的项目。可以丢弃子类别。

我到底该怎么做?我使用 Python3 很短时间,我知道如何将以上内容保存为准备用于 Excel 的 csv 文件,但我不知道如何以我想要的方式构造它。如果我使用列表将所有 MainCategories 放入一个列表,然后将项目计数放入另一个列表,我如何维护 MainCategories 和项目计数之间的关系?我应该做点别的吗?也许使用字典?任何帮助将不胜感激,因为我不知道该怎么做。

【问题讨论】:

  • 您的一个建议,使用dict,是一个很好的起点。我的解决方案以此为基础。

标签: python list pandas csv dictionary


【解决方案1】:

这是通过collections.defaultdictpandas 库提供的一种解决方案,给定一个列表lst

import pandas as pd
from collections import defaultdict

d = defaultdict(lambda: defaultdict(int))

for i in lst:
    for j in i[1:]:
        d[i[0]][j[0]] += 1

df = pd.DataFrame(index=sorted(d.keys()),
                  columns=sorted(set.union(*map(set, d.values()))))

for k, v in d.items():
    for w in v:
        df.loc[k, w] = d[k][w]

df = df.fillna(0).rename_axis('Name').reset_index()

然后您可以轻松地将其发送到 Excel:

df.to_excel('file.xlsx', index=False)

结果:

    Name  MainCategory1  MainCategory2  MainCategory3  MainCategory4  \
0  Name1              1              0              0              0   
1  Name2              0              3              1              1   
2  Name3              0              0              1              0   

   MainCategory5  MainCategory6  
0              0              0  
1              3              0  
2              0              1  

【讨论】:

  • 太棒了!谢谢jp! :)
猜你喜欢
  • 2021-07-18
  • 2015-04-01
  • 2018-03-25
  • 1970-01-01
  • 2021-04-24
  • 2019-04-29
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
相关资源
最近更新 更多