【问题标题】:CSV File Transpose Column to Row in PythonCSV文件在Python中将列转置为行
【发布时间】:2019-09-20 14:30:36
【问题描述】:

我已经为此伤透了脑筋,我可能只需要退后一步。

我有一个这样的 CSV 文件:(虚拟数据 - 可能有 1-20 个参数)

汽车、姓名、年龄、颜色

福特,迈克,45,蓝

大众,彼得,67,黄色

需要

汽车、参数、价值

福特,NAME,迈克

福特,年龄,45

福特,颜色,蓝色

大众,姓名,彼得

大众,AGE,67

大众,颜色,黄色

我在看:

How to transpose a dataset in a csv file?

How to transpose a dataset in a csv file?

Python writing a .csv file with rows and columns transpose

但我认为因为我想保持 CAR 列静态,Python zip 函数可能无法破解它..

对这位阳光明媚的星期五大师有什么想法吗?

问候!

>

【问题讨论】:

    标签: python csv


    【解决方案1】:

    使用pandas:

    df_in = read_csv('infile.csv')
    df_out = df_in.set_index('CAR').stack().reset_index()
    df_out.columns = ['CAR', 'PARAMETER', 'VALUE']
    df_out.to_csv('outfile.csv', index=False)
    

    输入输出示例:

    >>> df_in
        CAR   NAME  AGE  COLOUR
    0  Ford   Mike   45    Blue
    1    VW  Peter   67  Yellow
    >>> df_out
        CAR PARAMETER   VALUE
    0  Ford      NAME    Mike
    1  Ford       AGE      45
    2  Ford    COLOUR    Blue
    3    VW      NAME   Peter
    4    VW       AGE      67
    5    VW    COLOUR  Yellow
    

    【讨论】:

    【解决方案2】:

    我可以使用 Python - Transpose columns to rows within data operation and before writing to file 并进行一些调整,现在一切正常。

    import csv
    
    with open('transposed.csv', 'wt') as destfile:
        writer = csv.writer(destfile)
        writer.writerow(['car', 'parameter', 'value'])
        with open('input.csv', 'rt') as sourcefile:
            for d in csv.DictReader(sourcefile):
                car= d.pop('car')
                for parameter, value in sorted(d.items()):
                    row = [car, parameter.upper(), value]
                    writer.writerow(row)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2017-11-30
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      相关资源
      最近更新 更多