【问题标题】:How to put multi array to one csv file with header Python如何将多个数组放入一个带有标题 Python 的 csv 文件
【发布时间】:2021-08-05 20:35:49
【问题描述】:

我有这样的列表,我从xlsx 文件加载

import pandas as pd
travel_df = pd.read_excel('./item.xlsx')
data = travel_df.to_dict('records')

data 这样的

data = 
[
    {
        'cat': 'A',
        'subCat': 'a1',
    },
    {
        'cat': 'A',
        'subCat': 'a2',
    },
    {
        'cat': 'B',
        'subCat': 'b1',
    },
    {
        'cat': 'B',
        'subCat': 'b2',
    },
    {
        'cat': 'B',
        'subCat': 'b3',
    },
]

我想把它放到CSV 这样的文件中,最好和最快的方法是什么

A     B
--------
a1    b1
a2    b2
      b3

【问题讨论】:

    标签: python pandas numpy csv


    【解决方案1】:

    您可以通过DataFrame()方法、pivot()方法和apply()方法来做到这一点:

    newdf=pd.DataFrame(data).pivot(columns='cat',values='subCat').apply(lambda x:sorted(x,key=pd.isna))
    

    最后过滤掉NaN's:

    newdf=newdf[~newdf.isna().all(1)]
    

    newdf的输出:

    cat   A     B
    0     a1    b1
    1     a2    b2
    2     NaN   b3
    

    现在,如果您想将其保存在 csv 文件中,请使用 to_csv() 方法

    【讨论】:

    • 如何避免重复记录?
    • 只需使用drop_duplicates() 方法即:newdf=newdf.drop_duplicates()
    猜你喜欢
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2021-11-15
    • 1970-01-01
    相关资源
    最近更新 更多