在 Pandas 的 DataFrame 中合併兩列文字
Ahmed Waheed
2023年1月30日
有時,使用資料集時,你需要組合兩列或更多列以形成一列。例如,你有一個資料集,其中名字和姓氏以列分隔,現在你需要全名列。下面列出了完成此任務的不同方法。
在以下各節中,我們將使用相同的 DataFrame
,如下所示:
import pandas as pd
data = [["Ali", "Azmat", "30"], ["Sharukh", "Khan", "40"], ["Linus", "Torvalds", "70"]]
df = pd.DataFrame(data, columns=["First", "Last", "Age"])
print(df)
輸出:
First Last Age
0 Ali Azmat 30
1 Sharukh Khan 40
2 Linus Torvalds 70
+
運算子方法
僅當你要合併相同資料型別的資料時,才使用+
運算子。
import pandas as pd
data = [["Ali", "Azmat", "30"], ["Sharukh", "Khan", "40"], ["Linus", "Torvalds", "70"]]
df = pd.DataFrame(data, columns=["First", "Last", "Age"])
df["Full Name"] = df["First"] + " " + df["Last"]
print(df)
輸出:
First Last Age Full Name
0 Ali Azmat 30 Ali Azmat
1 Sharukh Khan 40 Sharukh Khan
2 Linus Torvalds 70 Linus Torvalds
df.map()
方法
你還可以使用 df.map()
函式合併兩列的文字。
import pandas as pd
data = [["Ali", "Azmat", "30"], ["Sharukh", "Khan", "40"], ["Linus", "Torvalds", "70"]]
df = pd.DataFrame(data, columns=["First", "Last", "Age"])
df["Full Name"] = df["First"].map(str) + " " + df["Last"]
print(df)
輸出:
First Last Age Full Name
0 Ali Azmat 30 Ali Azmat
1 Sharukh Khan 40 Sharukh Khan
2 Linus Torvalds 70 Linus Torvalds
df.apply()
方法
join()
函式也用於連線字串。我們可以使用 df.apply()
函式將其應用於我們的 DataFrame.df.apply()
函式用於在特定軸上應用另一個函式。
import pandas as pd
data = [["Ali", "Azmat", "30"], ["Sharukh", "Khan", "40"], ["Linus", "Torvalds", "70"]]
df["Full Name"] = df[["First", "Last"]].apply(" ".join, axis=1)
print(df)
輸出:
First Last Age Full Name
0 Ali Azmat 30 Ali Azmat
1 Sharukh Khan 40 Sharukh Khan
2 Linus Torvalds 70 Linus Torvalds
Series.str.cat()
方法
我們也可以使用 Series.str.cat()
方法將 Series
/ Index
中的字串與給定的分隔符連線起來。
import pandas as pd
data = [["Ali", "Azmat", "30"], ["Sharukh", "Khan", "40"], ["Linus", "Torvalds", "70"]]
df["Full Name"] = df["First"].str.cat(df["Last"], sep=" ")
print(df)
輸出:
First Last Age Full Name
0 Ali Azmat 30 Ali Azmat
1 Sharukh Khan 40 Sharukh Khan
2 Linus Torvalds 70 Linus Torvalds
df.agg()
方法
與 df.apply()
相同,此方法還用於在指定軸上應用特定函式。
import pandas as pd
data = [["Ali", "Azmat", "30"], ["Sharukh", "Khan", "40"], ["Linus", "Torvalds", "70"]]
df["Full Name"] = df[["First", "Last"]].agg(" ".join, axis=1)
print(df)
輸出:
First Last Age Full Name
0 Ali Azmat 30 Ali Azmat
1 Sharukh Khan 40 Sharukh Khan
2 Linus Torvalds 70 Linus Torvalds