如何修复两个数据集之间的联接

时间:2019-04-19 16:40:34

标签: python-3.x pandas join

问题:当我尝试合并或联接两个数据集时,设置相同的索引会生成具有重复项的数据集。

创建第一个数据框(UNI):

import csv
import pandas as pd
import os
import os.path

fullName=os.getcwd()
full_filename = os.path.join(fullName,'Rankings.csv')
file_stream = open(full_filename, mode='r', newline='')

reader = csv.reader(file_stream, delimiter=",")

# read and ignore the first line
header = next(reader)
data = []
# read the remaining part of the file
for i in range(2000):
info = next(reader)
data += [info]
file_stream.close()

dfUNI = pd.DataFrame(data)
dfUNI.columns = header
#I Renamed column 1 to be able to merge the two datasets with the same "Name" column
cols = dfUNI.columns.get_values()
cols[1] = 'Name'
dfUNI.columns = cols

创建第二个数据帧(费用):

full_filename = os.path.join(fullName,'Fees.csv')
file_stream = open(full_filename, mode='r',      newline='',encoding="ISO-8859-1");
#I used encoding to remove reading problems
reader = csv.reader(file_stream, delimiter=",")
# read and ignore the first line
header = next(reader)
data = []
# read the remaining part of the file
for i in range(200):
    info = next(reader)
    data += [info]
file_stream.close()

dfFees = pd.DataFrame(data)
dfFees.columns = header
del dfUNI["international"]
del dfUNI["income"]
del dfUNI["female_male_ratio"]
del dfUNI["student_staff_ratio"]
del dfUNI["year"]
dfUNI.set_index("Name")
dfFees.set_index("Name")
dfFees

一起加入他们:

df=dfUNI.set_index("Name")
df2=dfFees.set_index("Name")
df.join(df2,how="outer")

我希望有一个数据集,其中dfFees / df2“(第二个)数据集中的信息被添加到"Name" / { {1}}(第一个)数据集。

1 个答案:

答案 0 :(得分:0)

首先,由于您正在使用pandas,因此您可能想简化在使用pd.read_csvdocumentation here)的csv中阅读的方式(也可以使用pathlib.Pathdoc)可简化路径操作,但我专注于pandas):

# Starting from scratch:

import csv
import pandas as pd
import os
import os.path

fullName=os.getcwd()
full_filename_UNI = os.path.join(fullName, "Rankings.csv")
full_filename_Fees = os.path.join(fullName, "Fees.csv")

dfUNI  = pd.read_csv(full_filename_UNI, delimiter=",")
dfFees = pd.read_csv(full_filename_UNI, delimiter=",", encoding="ISO-8859-1")

然后,您可以使用.renamedoc)重命名该列,并使用.dropdoc)代替del dfUNI["something"]。不要忘记其中的“ inplace”自变量,这样您就不必像dfUNI = dfUNI.replace(...)那样每次都重新定义变量。

# Start of cleanup for dfUNI ->
dfUNI.rename(index=str, columns={dfUNI.columns[0]: "Name"}, inplace=True)

# Start of cleanup for dfFee ->
colNameDropList = ["international", "income", "female_male_ratio", "student_staff_ratio", "year"]
dfFees.drop(columns=colNameDropList, inplace=True)

# Set the index for both (use inplace!):
dfUNI.set_index("Name", inplace=True)
dfFees.set_index("Name", inplace=True)

现在是您真正需要的部分:您需要使用left join。熊猫对其数据框使用许多SQL-esk方法。

dfFINAL = dfUNI.join(dfFees, how="left") # "left" is the default btw

,您可以使用on方法的“ .join”参数来代替预先设置索引:

dfFINAL = dfUNI.join(dfFees, how="left", on="Name")

由于执行“外部联接”,因此获得重复项,这会将数据放在一起并且不会丢失任何数据。 (签出this。)