python - 想使用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 文件中提取与柴油行相对应的值
解决方案
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)
推荐阅读
- python - 匹配字符串,直到找到一个字符,该字符也包含在可选字段中
- c# - 使用通用类型'SignInManager
' 需要 2 个类型参数 - reactjs - 电子中的 Mobx 未捕获语法错误
- php - Wordpress Echo 帖子计数
- ios - 自定义 URL 方案 Obj-C iOS Xcode
- couchbase - 使用 Couchbase N1QL 更新列表的多个元素
- json - 从对象到数组的 JSON 响应
- c++ - 如何组织 git 工作流来修复错误并同时引入新功能
- neural-network - 如何微调动量优化器的超参数?
- django - PYMQI 返回数据类型问题