将两个Pandas系列合并为一个数据框架

将两个Pandas系列合并为一个数据框架

在这篇文章中,我们将学习如何将两个系列合并成一个数据框架?在开始之前,让我们看看什么是系列?
Pandas Series是一个一维标签数组,能够容纳任何数据类型。换句话说,Pandas系列不过是excel表格中的一列。

在pandas中,有几种方法可以串联两个系列。以下是其中一些方法。

方法1:使用pandas.concat()

该方法完成了沿轴进行连接操作的所有繁重工作,同时对其他轴上的索引(如果有的话)执行可选的集合逻辑(union或intersection)。

代码:

# import pandas library
import pandas as pd
  
# this user defines function
# creates a series
# from the passed list.
def createSeries (series_list):
    
  # create a series
  series_list = pd.Series(series_list)
    
  return series_list
  
# create a series of students
students = createSeries(['ABC', 'DEF',
                         'GHI', 'JKL',
                         'MNO', 'PQR'])  
# create a series of subjects
subject = createSeries(['C++', 'C#', 
                        'RUBY', 'SWIFT',
                        'GO', 'PYTHON'])
# create a series of marks
marks = createSeries([90, 30, 
                      50, 70, 
                      80, 60])
# create a dictonary
data = {"students": students,
        "subject": subject,
        "marks": marks}
  
# Concatenating the series side
# by side as depicted by axis=1
# If you want to concatenate the 
# series one below the other
# change the axis to zero.
df = pd.concat(data,
               axis = 1)
  
# show the dataframe
df

输出:

将两个Pandas系列合并为一个数据框架

方法2:使用系列.append()

这个方法是concat的一个快捷方式。这个方法沿轴=0连接,即行。Series.append()可以取多个对象进行连接。

代码:

# import pandas library
import pandas as pd
  
# create a series
a = pd.Series(["ABC", "DEF", 
               "GHI"])
  
# create a series
b = pd.Series(["JKL", "MNO", 
               "PQR"])
  
# combine two series then
# create a dataframe
df = pd.DataFrame(a.append(b, 
                  ignore_index = True))
# show the dataframe
df

输出:

将两个Pandas系列合并为一个数据框架

方法3:使用pandas.merge()

Pandas有高性能的内存连接操作,这与SQL等RDBMS非常相似。合并可用于所有数据帧或命名系列对象之间的数据库连接操作。在这种情况下,你必须向系列对象传递一个额外的参数 “名称”。

代码:

# import pandas library
import pandas as pd
  
# create a series
a = pd.Series(["C++", "JAVA", 
               "PYTHON", "DBMS",
               "C#"], name = "subjects")
  
# create a series
b = pd.Series(["30", "60", 
               "90", "56", 
               "50"], name = "marks")
  
# merge both series 
df = pd.merge(a, b, right_index = True,
               left_index = True)
# show the dataframe
df

输出:

将两个Pandas系列合并为一个数据框架

方法4:使用Dataframe.join() .

这种方法也可用于连接两个系列,但你必须将一个系列转换为数据框架。

代码:

# import pandas library
import pandas as pd
  
# create a series
a = pd.Series(["C++", "JAVA", 
               "PYTHON", "DBMS", 
               "C#"], name = "subjects")
  
# create a series
b = pd.Series(["30", "60", 
               "90", "56", 
               "50"], name = "marks")
  
# create a dataframe
a = pd.DataFrame(a)
  
# add series 'b' 
# into dataframe 'a'
df = a.join(b)
  
# show the dataframe
df

输出:

将两个Pandas系列合并为一个数据框架

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程