繁体   English   中英

使用 pandas python 从 csv 文件中以特定方式读取

[英]Read in a specific way from a csv file with pandas python

我在 csv 文件中有一个数据,这里是一个示例:

firstnb,secondnb,distance
901,19011,459.73618164837535
901,19017,492.5540450352788
901,19018,458.489289271722
903,13019,167.46632044684435
903,13020,353.16001204909657

所需的 output:

901,19011,19017,19018
903,13019,13020

正如您在 output 中看到的,我想使用 firstnb 列 (901/903)

并在每个旁边放上 secondnb 我相信你可以从所需的 output 中比我的解释更好地理解:D

到目前为止我尝试的是以下内容:

import pandas as pd
import csv
df = pd.read_csv('test.csv')
    with open('neighborList.csv','w',newline='') as file:
        writer = csv.writer(file)
        secondStation = []
        for row in range(len(df)):
            firstStation = df['firstnb'][row]
            for x in range(len(df)):
                if firstStation == df['firstnb'][x]:
                    secondStation.append(df['secondnb'][x])
                    # line = firstStation ,secondStation
                    # writer.writerow(line)        
            print(firstStation,secondStation)
            secondStation = []

我的代码 output 这个:

901 [19011, 19017, 19018]
901 [19011, 19017, 19018]
901 [19011, 19017, 19018]
903 [13019, 13020]
903 [13019, 13020]

Pandas 有一个内置的 function 来执行此操作,称为 groupby:

df = pd.read_csv(YOUR_CSV_FILE) 
df_grouped = list(df.groupby(df['firstnb'])) # group by first column

# chain keys and values into merged list
for key, values in df_grouped:
    print([key] + values['secondnb'].tolist())

这里我只打印子列表; 您可以将它们以您喜欢的任何格式(字符串、整数等)保存到新的 csv 中

首先,我按firstnb对数据进行分组,使用aggregate function 在secondnb中创建值list

df[['firstnb','secondnb']].groupby('firstnb').aggregate(func=list).to_dict()

通过把它变成一个dict ,我们得到:

{'secondnb': {901: [19011, 19017, 19018], 903: [13019, 13020]}}

我不太清楚最终的 output 应该是什么(纯字符串、列表……),但从这里开始,很容易生成您想要的任何内容。

例如,列表列表:

intermediate = df[['firstnb','secondnb']].groupby('firstnb').aggregate(func=list).to_dict()

[[k] + v for k,v in intermediate['secondnb'].items()]

结果:

[[901, 19011, 19017, 19018], [903, 13019, 13020]]
def toList(a):
  res = []
  for r in a:
    res.append(r)
  return res
df.groupby('firstnb').agg(toList)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM