如何合并 pandas 中的两列(附示例)
您可以使用以下语法将 pandas DataFrame 中的两个文本列合并为一个:
df[' new_column '] = df[' column1 '] + df[' column2 ']
如果其中一列还不是字符串,您可以使用astype(str)命令将其转换:
df[' new_column '] = df[' column1 ']. astype ( str )+df[' column2 ']
您可以使用以下语法将多个文本列合并为一个:
df[' new_column '] = df[[' col1 ', ' col2 ', ' col3 ', ...]]. agg (' '. join , axis= 1 )
以下示例展示了如何在实践中组合文本列。
示例 1:合并两列
以下代码展示了如何在 pandas DataFrame 中将两个文本列合并为一列:
import pandas as pd #create dataFrame df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'], ' first ': ['Dirk', 'Kobe', 'Tim', 'Lebron'], ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'], ' points ': [26, 31, 22, 29]}) #combine first and last name column into new column, with space in between df[' full_name '] = df[' first '] + ' ' + df[' last '] #view resulting dataFrame df team first last points full_name 0 Mavs Dirk Nowitzki 26 Dirk Nowitzki 1 Lakers Kobe Bryant 31 Kobe Bryant 2 Spurs Tim Duncan 22 Tim Duncan 3 Cavs LeBron James 29 LeBron James
我们已经将名字和姓氏列连接在一起,中间有一个空格,但我们也可以使用不同的分隔符,例如连字符:
#combine first and last name column into new column, with dash in between df[' full_name '] = df[' first '] + ' - ' + df[' last '] #view resulting dataFrame df team first last points full_name 0 Mavs Dirk Nowitzki 26 Dirk - Nowitzki 1 Lakers Kobe Bryant 31 Kobe - Bryant 2 Spurs Tim Duncan 22 Tim - Duncan 3 Cavs Lebron James 29 Lebron - James
示例 2:转换为文本并合并两列
以下代码显示如何将列转换为文本,然后将其连接到另一列:
import pandas as pd #create dataFrame df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'], ' first ': ['Dirk', 'Kobe', 'Tim', 'Lebron'], ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'], ' points ': [26, 31, 22, 29]}) #convert points to text, then join to last name column df[' name_points '] = df[' last '] + df[' points ']. astype ( str ) #view resulting dataFrame df team first last points name_points 0 Mavs Dirk Nowitzki 26 Nowitzki26 1 Lakers Kobe Bryant 31 Bryant31 2 Spurs Tim Duncan 22 Duncan22 3 Cavs LeBron James 29 James29
示例 3:合并两列以上
以下代码展示了如何将多列合并为一列:
import pandas as pd #create dataFrame df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'], ' first ': ['Dirk', 'Kobe', 'Tim', 'Lebron'], ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'], ' points ': [26, 31, 22, 29]}) #join team, first name, and last name into one column df[' team_and_name '] = df[[' team ', ' first ', ' last ']]. agg (' '. join , axis= 1 ) #view resulting dataFrame df team first last points team_name 0 Mavs Dirk Nowitzki 26 Mavs Dirk Nowitzki 1 Lakers Kobe Bryant 31 Lakers Kobe Bryant 2 Spurs Tim Duncan 22 Spurs Tim Duncan 3 Cavs Lebron James 29 Cavs Lebron James