首页 > 解决方案 > 想使用python从csv文件中提取特定行

问题描述

Fuel Type,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018
Diesel,7,4,17,43,138,346,681,1412,3206,5976,10364,15514,17253
Diesel-Electric,0,0,0,0,0,0,0,6,17,23,22,22,21
Electric,1,1,1,1,2,2,3,0,1,1,12,314,560
Petrol,471707,513375,545994,571629,589034,596947,609792,612654,605511,587900,578977,574443,569673
Petrol-CNG,214,248,2440,2678,2706,2642,2410,2253,2100,1932,1682,1006,386
Petrol-Electric,379,1057,1999,2637,3305,3786,4684,5020,5727,6371,10075,20751,27179
Petrol-Electric (Plug-In),0,0,0,0,0,0,0,0,47,108,125,206,380

从上面的 csv 文件中提取与柴油行相对应的值

标签: pythonpandas

解决方案


import pandas as pd
df = pd.read_csv('filename', sep=",",header=0)
diesel = df[df["Fuel Type"] == 'Diesel']

从评论中编辑,以获取燃料类型中包含柴油的所有行

diesel = df[df["Fuel Type"].str.contains('Diesel')]

如果你不想使用 pandas,你也可以简单地使用

with open('filename', 'r') as f:
    line = f.readline()
    if line[:6] == "Diesel":
        break
print(line)

推荐阅读