如何在Pandas中合并不同长度的DataFrames
在这篇文章中,我们将讨论如何在Pandas中合并两个不同长度的数据帧。它可以使用merge()方法来完成。
语法:
DataFrame.merge(parameters)
Python
下面是一些例子,描述了如何使用上述方法合并不同长度的数据帧。
示例 1:
下面是一个合并两个不同长度的学生数据框架的程序。
# importing pandas module
import pandas as pd
# create a list that contains
# student id of subject 1
list1 = [7058, 7059, 7075, 7076]
# create a list that contains
# student id of subject 2
list2 = [7058, 7059, 7012, 7075, 7076]
# create a list that contains
# student names of subject 1
list11 = ["Sravan", "Jyothika", "Deepika",
"Kyathi"]
# create a list that contains
# student names of subject 2
list22 = ["Sravan", "Jyothika", "Salma",
"Deepika", "Kyathi"]
# pass list1 and list11 to the
# dataframe1
dataframe1 = pd.DataFrame(
{"Student ID": list1, "Student Name": list11})
print('First data frame:')
display(dataframe1)
# pass list2 and list22 to the
# dataframe1
dataframe2 = pd.DataFrame(
{"Student ID": list2, "Student Name": list22})
print('Second data frame:')
display(dataframe2)
# apply merge function to merge the
# two dataframes
mergedf = dataframe2.merge(dataframe1, how='left')
print('Merged data frame:')
display(mergedf)
Python
输出:
示例 2:
下面是另一个程序,用于合并一个长度为4的数据框和另一个长度为9的数据框。
# importing pandas module
import pandas as pd
# create a list that contains
# student id of subject 1
list1 = [7058, 7059, 7075, 7076]
# create a list that contains
# student id of subject 2
list2 = [7058, 7059, 7012, 7075, 7076,
7034, 7046, 7036, 7015]
# create a list that contains
# student names of subject 1
list11 = ["Sravan", "Jyothika", "Deepika",
"Kyathi"]
# create a list that contains
# student names of subject 2
list22 = ["Sravan", "Jyothika", "salma",
"Deepika", "Kyathi", "meghana",
"pranathi", "bhanu", "keshav"]
# pass list1 and list11 to the
# dataframe1
dataframe1 = pd.DataFrame(
{"Student ID": list1, "Student Name": list11})
print('First data frame:')
display(dataframe1)
# pass list2 and list22 to the
# dataframe1
dataframe2 = pd.DataFrame(
{"Student ID": list2, "Student Name": list22})
print('Second data frame:')
display(dataframe2)
# apply merge function to merge
# the two dataframes
mergedf = dataframe2.merge(dataframe1, how='inner')
print('Merged data frame:')
display(mergedf)
Python
输出: