如何在Pandas DataFrame中串联列值

如何在Pandas DataFrame中串联列值

很多时候,我们需要将不同列中的值合并为一列。这方面的用例有很多,比如将列表中人的姓和名合并,将日、月、年合并成一列日期,等等。现在我们将通过一些例子来看看我们如何实现这个目标。

例子1:在这个例子中,我们将把两列名字和姓氏合并为一列名称。为了实现这一目标,我们将使用map函数。

import pandas as pd
from pandas import DataFrame 
   
# creating a dictionary of names
Names = {'FirstName':['Suzie','Emily','Mike','Robert'],
         'LastName':['Bates','Edwards','Curry','Frost']}
   
# creating a dataframe from dictionary
df = DataFrame(Names, columns=['FirstName','LastName'])
print(df)
   
print('\n')
   
# concatenating the columns
df['Name'] = df['FirstName'].map(str) + ' ' + df['LastName'].map(str)
print(df)
Python

输出:
如何在Pandas DataFrame中串联列值?

如何在Pandas DataFrame中串联列值?

实例2:同样,我们可以在一个数据框架中串联任何数量的列。让我们通过另一个例子来看看如何将日、月、年这三个不同的列串联到一个单一的Date列中。

import pandas as pd
from pandas import DataFrame 
  
# creating a dictionary of Dates
Dates = {'Day': [1, 29, 23, 4, 15], 
        'Month': ['Aug', 'Feb', 'Aug', 'Apr', 'Mar'], 
        'Year': [1947, 1983, 2007, 2011, 2020]}
  
# creating a dataframe from dictionary
df = DataFrame(Dates, columns = ['Day', 'Month', 'Year'])
print (df)
  
print('\n')
  
# concatenating the columns
df['Date'] = df['Day'].map(str) + '-' + df['Month'].map(str) + '-' + df['Year'].map(str)
print (df)
Python

输出:

如何在Pandas DataFrame中串联列值?

如何在Pandas DataFrame中串联列值?

示例 3:

我们可以进一步推进这个过程,将多个不同数据框架的多个列串联起来。在这个例子中,我们将数据框架df1和df2的列合并为一个数据框架。

import pandas as pd
from pandas import DataFrame 
  
# creating a dictionary of Dates
Dates = {'Day': [1, 1, 1, 1], 
        'Month': ['Jan', 'Jan', 'Jan', 'Jan'], 
        'Year': [2017, 2018, 2019, 2020]} 
  
# creating a dataframe from dictionary
df1 = DataFrame(Dates, columns = ['Day', 'Month', 'Year']) 
  
# creating a dictionary of Rates
Rates = {'GDP': [5.8, 7.6, 5.6, 4.1], 
         'Inflation Rate': [2.49, 4.85, 7.66, 6.08]} 
  
# creating a dataframe from dictionary
df2 = DataFrame(Rates, columns = ['GDP', 'Inflation Rate'])
  
# combining columns of df1 and df2
df_combined = df1['Day'].map(str) + '-' + df1['Month'].map(str) + '-' + df1['Year'].map(str) + ': ' + 'GDP: ' + df2['GDP'].map(str) + '; ' + 'Inflation: ' + df2['Inflation Rate'].map(str)
print (df_combined)
Python

输出:

如何在Pandas DataFrame中串联列值?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册