首页 > 解决方案 > 在从其他两个 CSV 文件派生的一个 CSV 文件中搜索特定信息(python)

问题描述

我有一个包含 3 个不同 CSV 文件的营养数据库。清理后,第一个文件包含两列:营养素id和营养素名称;第二个文件包含两列:食物 ID 和食物描述(名称);最后,第三个文件包含三列:营养素 id、食物 id 和数量(该食物中的营养素)。由于有几百万行,我不能每次都单独打开每个文件,查看哪个id对应哪个营养素或食物。所以我正在尝试创建一个代码,它将读取所有三个文件,然后在 id 列中搜索 nut (来自第一个文件)和 food (来自第二个文件)的匹配项,用名称替换 id 并返回 3列:营养名称、食物名称、数量。现在,有一个复杂的地方,即:在 1 和 2 文件中,行是按 id-s 排序的,而在第三个文件(有数量)中,这些行按 nutrition_id 排序(意味着食物 id-s 列是混乱的)。所以我不能只合并三个文件,或者用第三个文件中的名称列替换 id 列......这是我的代码示例,它不返回我需要的内容。我对此很困惑,因为我在互联网上找不到答案。谢谢!

#-*- coding: utf-8 -*- 

"""
Created on Fri Nov  8 17:38:45 2019

@author: user
"""
import pandas as pd 
#%% reading csv files 

#read the first scv file with nutrient_name, nutrient_id
df1 = pd.read_csv('nutrient.csv', low_memory=False)
print(df1)

#read specific columns from the first csv file
df1 = pd.read_csv('nutrient.csv', usecols = ['id', 'name'], low_memory=False)
df1.rename(columns={'name' : 'nut_name'}, inplace = True)
print(df1)

#read the second scv file with food_id and food_name , read specific columns 
df2 = pd.read_csv('food.csv', usecols = ['fdc_id', 'description'], low_memory=False)
print(df2)

#read the third csv file with food_id, nutrient_id and nutrient amount
df3 = pd.read_csv('food_nutrient.csv', usecols=['fdc_id','nutrient_id', 'amount'], low_memory=False)
print(df3)

#%% create a list of rows from each csv file 
# Create an empty list 1
Id_list =[] 
Name_list = []

# Iterate over each rowin first csv file 
for index, rows in df1.iterrows(): 

# append the list to the final list 
Id_list.append(rows.id)
Name_list.append(rows.nut_name)


# Print the list 
print(Id_list[:10])
print(Name_list[:10])  

# Create an empty list 2
Food_id_list =[]
Food_name_list =[] 

# Iterate over each rowin seconf csv file 
for index, rows in df2.iterrows(): 

# append the list to the final list 
Food_id_list.append(rows.fdc_id)
Food_name_list.append(rows.description)

print(Food_id_list[:10])
print(Food_name_list[:10])

# Create an empty list 1
Amount_list =[] 
Name_list1 = []
Food_name1 = []

# Iterate over each rowin third csv file 
for index, rows in df3.iterrows(): 

# append the list to the final list 
Amount_list.append(rows.amount)
Name_list1.append(rows.nutrient_id)
Food_name1.append(rows.fdc_id)

# Print the list 
print(Amount_list[:10])
print(Name_list1[:10])
print(Food_name1[:10])

#%% search in the third csv only rows, where amount of the certain nut in certain food is not empty 
value 
for i in Name_list:
   #for j in Food_name_list:
    if i in df3['nutrient_id']:
        print(df3.loc[i, 'amount'])

提前致谢!

标签: python-3.xcsv

解决方案


这正是创建 SQL 的目的。SQL 的join命令连接多个表。在玩了很多 Pandas 之后,我强烈建议学习一门简单的 SQL 课程,或者首先尝试阅读一个简单的SQL join教程,因为这在很大程度上是一个 SQL 入门问题。


推荐阅读