【问题标题】:Sort, group and calculate average in csv python在 csv python 中排序、分组和计算平均值
【发布时间】:2018-11-13 23:55:38
【问题描述】:

我有一个大的 4 列 csv 文件,其中包含随机值,我需要按特定列 ID 对行进行分组,然后在另一个文件中平均坐标。另外,我想保留小数位数。

ID, Latitude, Longitude, Cluster
1, 22.29124068, 19.59633257, 500
2, 22.28295135, 19.85912179, 214
3, 22.30154457, 19.65304535, 500
4, 22.29546953, 19.76508808, 214
5, 22.3322929, 19.75290081, 422
etc...

所以我需要做的是从 col[1] 和 col[2] 计算该文件中每个唯一集群 col[3] 的平均坐标并返回结果。

输出文件应该是:

ID, Latitude, Longitude, Cluster
1, <average_latitude_214 cluster>, <average_longitude_214 cluster>, 214
1, <average_latitude_500 cluster>, <average_longitude_500 cluster>, 500
and so on...

【问题讨论】:

  • 太棒了..开始编码。遇到问题就回来。 SO 是关于修复你的代码——而不是实现你的想法。请再次查看how to askon-topic,如果您有任何问题,请将您的代码提供为minimal verifyable complete example。如果您遇到错误,请将错误消息逐字(逐字)复制并粘贴到您的问题中。
  • 谢谢@PatrickArtner!我设法对数据进行了排序,但我找不到关于如何平均每个集群的数据的示例

标签: python pandas csv sorting average


【解决方案1】:

您可以使用 Python 的 defaultdict 创建具有相同集群的所有条目的列表。然后您可以从中计算每个集群的平均值并将该行写入您的输出 CSV 文件:

from collections import defaultdict
import csv

data = defaultdict(list)

with open('input.csv', newline='') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)

    for row in csv_input:
        row[1] = float(row[1])
        row[2] = float(row[2])
        data[row[3]].append(row)

with open('output.csv', 'w', newline='') as f_output:        
    csv_output = csv.writer(f_output)
    csv_output.writerow(header)

    for id, (cluster, items) in enumerate(sorted(data.items()), start=1):
        latitude = sum(i[1] for i in items) / len(items)
        longitude = sum(i[2] for i in items) / len(items)

        csv_output.writerow([id, latitude, longitude, cluster])

这将创建一个 output.csv 文件,其中包含:

ID,Latitude,Longitude,Cluster
1,22.289210439999998,19.812104935,214
2,22.3322929,19.75290081,422
3,22.296392625000003,19.62468896,500

【讨论】:

    【解决方案2】:

    如果您愿意使用第三方库,可以使用pandas

    import pandas as pd
    
    # read csv file
    df = pd.read_csv('file_in.csv')
    
    # perform groupby
    res = df.groupby('Cluster')[['Latitude', 'Longitude']].mean().reset_index()
    
    print(res)
    
    #    Cluster   Latitude  Longitude
    # 0      214  22.289210  19.812105
    # 1      422  22.332293  19.752901
    # 2      500  22.296393  19.624689
    
    # write to csv
    res.to_csv('file_out.csv', index=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2014-11-04
      • 1970-01-01
      相关资源
      最近更新 更多