【问题标题】:CSV file - handle row and columns with pythonCSV 文件 - 使用 python 处理行和列
【发布时间】:2019-03-22 12:05:25
【问题描述】:

你能帮帮我吗?

我有关于酒店的 CSV 数据集文件并包含许多列。我需要处理酒店名称和评论。

如何将酒店名称行转换为列?合并每个酒店的评论并将输出保存到新的 CSV 文件中?

我使用 Python 3.7

更新:首先感谢cmets

对不起,我必须假设输出的形状

我有超过 1400 家酒店

hotel-name     reviews 
Hotel Arena    love it
Hotel Arena    great
Hotel Arena    good
Hotel Arena    ........

the output will be :

hotel 1   hotel 2  hotel 3  .......
love it   stay     not bad
great     old      ..... 
good      ...      .......
..        
...         
....       

【问题讨论】:

  • 为您的问题提供输入、您的代码、您遇到的问题以及预期的输出。 Stack Overflow 不是获取免费代码的地方

标签: python file csv row multiple-columns


【解决方案1】:

如果我正确理解您的问题,您有一个包含多行的 csv 文件,每一行都有一个酒店的评论。

如果是这样,你可以使用这样的东西:

import pandas as pd

df = pd.DataFrame({'hotel': ['A', 'A', 'B', 'B', 'A', 'C'], 'rating': [1, 1, 2, 4, 3, 5]})

df.groupby('hotel').aggregate(lambda x: list(x))

DF 输出为:

  hotel  rating
0     A       1
1     A       1
2     B       2
3     B       4
4     A       3
5     C       5

在分组之后:

          rating
hotel           
A      [1, 1, 3]
B         [2, 4]
C            [5]

您必须为此安装 pandas 和 read your csv file with pandas(这很容易)。

【讨论】:

    【解决方案2】:

    您可以使用CSV library 来执行此操作。假设一个像这样的 csv 文件:

    name,review,comments
    A,nice,blabla
    B,notnice,bleble
    

    您可以按列过滤行:

    import csv
    
    if __name__ == "__main__":
        file = open('file.csv', 'rb')
        for row in csv.DictReader(file, delimiter = ','):
            print (row['name'],row['review']) 
    

    印刷:

    ('A', 'nice')
    ('B', 'notnice')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 2016-02-24
      • 2022-09-27
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多