【问题标题】:CSV Parsing Python, outputting certain rows that have an specific valueCSV Parsing Python,输出具有特定值的某些行
【发布时间】:2017-06-21 20:51:53
【问题描述】:

我想使用 python 来解析 CSV 文件,并且只输出具有特定值的某些行。这是我到现在为止的代码,

import csv  

f = open('alerts2.csv')
csv_f = csv.reader(f)
li1 = []
header = next(csv_f)
for row in csv_f:

    # li1.append(row[5])
    # li1.append(row[0]) 
    severity = int(row[0]) #Has The the integer value from 10 - 40
    Status = str(row[1])
    PolicyName = str(row[2])
    PolicyBlockName = str(row[3])
    PolicyRuleName = str(row[4])
    Summary = str(row[5])
    li1.append(severity)
    li1.append(Summary) # string variables
print li1
f.close()

这会输出严重性和摘要中的所有值,但我希望它仅在严重性值为 "10" 时才输出严重性和摘要的数据。 我正在考虑使用列表“li1”并搜索列表,如果找到值“10”,则输出这些值。有什么建议么??我是python新手。

【问题讨论】:

    标签: python python-2.7 csv parsing


    【解决方案1】:
    import pandas as pd
    
    alerts_df = pd.DataFrame.from_csv('alerts2.csv', index_col=None)
    print alerts_df[alerts_df['severity'] == 10]['Summary']
    

    【讨论】:

      【解决方案2】:

      只需将此检查添加到 csv 行的循环中:

      for row in csv_f:
          severity = int(row[0])
          if severity != 10:
              continue
      

      如果 severity 的值不是 10,则循环将 continue 处理下一行,并且不对当前行执行任何后续操作。

      【讨论】:

      • 谢谢,但你能解释一下你的解决方案吗?谢谢。
      • python 文档中有一个关于continue statements in for loops 的部分。希望有帮助!
      猜你喜欢
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 2021-10-10
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多