【问题标题】:Compare two lists in python and save results in a separate list比较python中的两个列表并将结果保存在单独的列表中
【发布时间】:2020-08-05 07:28:00
【问题描述】:

到目前为止我的代码:

import csv

myIds = ['1234','3456','76']
countries = []

# open the file
with open('my.csv', 'r') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables and assign to lists
myFileIds = data['id']
myFileCountry = data['country']
listfromfile = [a + " " + b for a, b in zip(myFileIds, myFileCountry)]

上面在 listfromfile 中给出了如下结果:

listfromfile = ['1 Uruguay', '2 Vatican', '1234 US', '3456 UK', '5678 Brazil','10111 Argentina','234567 Spain']

我的目标是列出在 my.csv 文件中出现 ID 的国家/地区,但 myIds 列表中的 id 也可能不会出现在 my.csv 文件中。然后我需要列表中的那个位置显示为“不受支持的国家/地区”。两个列表的 myIds 和国家应该具有相同的长度,所以我会知道我列表中的第一个 id 对应于另一个列表中的第一个国家等。期望的结果:

myIds = ['1234','3456','76']
countries = ['US', 'UK', 'Unsupported Country']

或者我正在尝试使用熊猫,但也没有运气:(

import pandas as pd

df=pd.read_csv('my.csv')
myIds = ['1234','3456','76']

countries = df.loc[df["id"].isin(myIds),"country"].tolist()

我的.csv:

id     country
1      Uruguay
2      Vatican
1234   US
3456   UK
5678   Brazil
10111  Argentina
234567 Spain

有人可以帮我解决这个问题吗?提前致谢!

【问题讨论】:

  • 假设文件中的文本与示例中的文本完全相同,要从文件中获取数据框:pd.read_csv("my.csv", sep=r'\s+') 您需要指定分隔符。检查我的答案是否有其他选择。

标签: python python-3.x pandas list csv


【解决方案1】:
 import pandas as pd

 myIds = ['1234','3456','76']

 df = pd.DataFrame(myIds, columns=['id'])

 fields=['id', 'country']

 df = df1
 df2 = pd.read_csv('my.csv', sep = ',', usecols=fields)
 df3 = df1.merge(df2, on="id", how='left')
 df3['country'].fillna('Unsupported Country', inplace=True)
 del df3['id']
 countries = df3['country'].tolist()

以上对我有用。但是,仍在尝试找到更简单的解决方案。

【讨论】:

  • @ketan-krishna-patil 早些时候提供了类似的解决方案。重复答案
【解决方案2】:

也许这对您的目的有用:

这假设您的文件数据与您在示例中的数据相同。否则,您可以拆分另一个字符。

>>> from collections import defaultdict
>>> country_data = defaultdict(lambda: 'Unsupported Country')
>>> 
>>> for line in open("my.csv", 'r'):
...     try:
...         id, country = line.split()
...         country_data[int(id)] = country
...         country_data[country] = int(id)
...     except ValueError:
...         pass # Row isn't in the right format. Skip it.
...         
>>> country_data['Vatican']
2
>>> country_data[2]
'Vatican'
>>> country_data['Moojoophorbovia']
'Unsupported Country'
>>> 

如果您不是通过假设您需要两个必须保持同步的列表来尝试将方形钉放入圆孔中 - 然后尝试将文件数据放入其中,上述可能会解决问题读取国家数据并通过 ID 索引访问它,或者从国家名称中获取 ID。

【讨论】:

    【解决方案3】:

    您可以使用数据框实现此目的。

    import pandas as pd
    input_df = pd.read_csv("test.csv")
    myIds = ['1234','3456','76']
    my_ids_df = pd.DataFrame(myIds,columns=['id']).astype(int)
    output_df = pd.merge(input_df, my_ids_df, on=['id'], how='right')
    output_df['country'] = output_df['country'].fillna('Unsupported Country')
    print(list(zip(output_df['id'].values.tolist(),output_df['country'].values.tolist())))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 2018-03-19
      • 2023-02-25
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多