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

问题描述 投票:1回答:1

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

创建第一个数据帧(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")到dfUNI / df(第一个)数据集的数据集。

python-3.x pandas join
1个回答
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。 Pandas为其数据帧使用了许多SQL-esk方法。

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

或者,不是事先设置索引,而是可以使用on方法的“.join”参数:

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

你得到了重复,因为你正在做一个“外连接”,它将数据抛在一起,不会错过任何一个。 (检查this。)

© www.soinside.com 2019 - 2024. All rights reserved.