在csv中搜索多个值并在列表中返回行

时间:2017-11-03 14:36:12

标签: python pandas csv

我有一个包含多行的CSV,一个字段命名为" Market"。我想要做的就是将每一行与我在列表中的市场联系点相匹配,但我似乎无法让它发挥作用。

到目前为止,我已尝试过以下方法:

PoC1 = ["Georgia", "Florida", "Alabama", "Mississippi"]
PoC2 = ["New York", "New Jersey", "Connecticut", "Pennsylvania"]
PoC3 = ["California", "Arizona", "Nevada", "Oregon"]

import pandas as pd

df = pd.read_csv("Markets.csv")
PoC1Markets = df[df['Market'] == PoC1]
PoC2Markets = df[df['Market'] == PoC2]
PoC3Markets = df[df['Market'] == PoC3]

但那并没有回报任何东西。作为参考,每行包含纬度/经度坐标和我期望返回的字母数字代码。我试图返回与市场联系点相关的每一行,并分别向他们发送一封电子邮件,其中包含CSV中各自的行。任何帮助,将不胜感激!

2 个答案:

答案 0 :(得分:2)

我不熟悉pandas,我可能会误解你的目标,但这样的事情会做你想要的吗?它会根据Market字段的值将.csv文件中的记录分成3个桶。

import csv

PoC1 = ["Georgia", "Florida", "Alabama", "Mississippi"]
PoC2 = ["New York", "New Jersey", "Connecticut", "Pennsylvania"]
PoC3 = ["California", "Arizona", "Nevada", "Oregon"]

PoC1Markets = []
PoC2Markets = []
PoC3Markets = []

with open('Markets.csv','rb') as input:
  reader = csv.DictReader(input)
  for record in reader:
    market = record['Market']
    if market in PoC1:
      PoC1Markets.append(record)
    if market in PoC2:
      PoC2Markets.append(record)
    if market in PoC3:
      PoC3Markets.append(record)
  print(PoC1Markets)

答案 1 :(得分:1)


在我提供的代码中有一些我看不到的东西,但我想我能理解你想要做什么。我想告诉你的是确保列出正确的列名和索引,这样你就不会感到困惑,正如@Paula Livingstone所提到的,我也确信它会返回一些东西。
也就是说,做这样的事情的最好方法是使用isin函数,例如:

data = df[df[header[0]].isin(list[0])]

希望它有所帮助。