【问题标题】:How to use Python to convert columns to rows如何使用 Python 将列转换为行
【发布时间】:2021-05-28 05:42:53
【问题描述】:

我有一个如下的 csv 输出文件(示例数据):

Score1 Main_Score Second_score LGA pred 5 0 1 1 0.89 5 1 0 1 0.79

答案应该是这样的;

Score1 ScoreType LGA pred 5 Main_Score 1 0.89 5 Second_score 1 0.79

任何帮助将不胜感激!!!

提前致谢

【问题讨论】:

    标签: python-3.x excel multiple-columns transformation


    【解决方案1】:

    这里是使用 if-else 的简单方法。

    import csv
    
    with open('input.csv') as f:
        #load csv
        reader = csv.reader(f)
        data = [row for row in reader]
        data.pop(0) #delete header
    
        #convert
        for i in range(len(data)):
            print(data[i])
            score_type = "MainScore" if int(data[i][1]) == 0 else "SecondScore" # <- convert it here
            data[i] = [data[i][0], score_type, data[i][3], data[i][4]]
    
        #save csv
        data.insert(0, ['Source1', 'ScoreType', 'LGA', 'pred']) #add header
        with open('output.csv', 'w',newline="") as f:
            writer = csv.writer(f)
            writer.writerows(data)
    

    输入 csv:

    Source1, Main_Score, Second_Score, LGA, pred
    5, 0, 1, 1, 0.89 
    5, 1, 0, 1, 0.79
    

    输出 csv:

    Source1,ScoreType,LGA,pred
    5,MainScore, 1, 0.89 
    5,SecondScore, 1, 0.79
    

    【讨论】:

    • 感谢您的反馈。不幸的是,我不能硬编码“Score_type”。因为我有 105 个不同的列需要转置为行。我知道,我的问题提供的信息非常有限。只是想如何在不硬编码列名的情况下动态转置
    • 那么,你的意思是输入的csv数据有105个ScoreTypes吗?输出的 csv 数据是否只包含四列,[Score1, Scoretype LGA pred]?
    • 输出 csv 包含 103 列。每列都有一个输出“0”或“1”。需要将列转换为行。不确定是否有办法动态提供列名。
    猜你喜欢
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多