- concat — pandas 層級:單純把資料黏在一起,無任何條件
- merge — pandas 層級:以共同的欄位或索引層級黏合
- join — DataFrame 層級:只以「索引」黏合
Example 1:基本 join — 以索引合併兩個 DataFrame #
import pandas as pd
df1 = pd.DataFrame({
"Age": [25,30,22]
}, index=["Alice", "Bob", "Cat"])
df2 = pd.DataFrame({
"City": ["HK", "Tokyo", "Sydney", "Taiwan"]
}, index=["Alice", "Bob", "Cat", "David"])
df1.join(df2)output:
Age City Alice 25 HK Bob 30 Tokyo Cat 22 Sydney
Example 2:索引不完全對應時 join — 缺的一邊補上 NaN #
import pandas as pd
df1 = pd.DataFrame({
"Age": [25,30,22, 40]
}, index=["Alice", "Bob", "Cat", "Peter"])
df2 = pd.DataFrame({
"City": ["HK", "Tokyo", "Sydney", "New York"]
}, index=["Alice", "Bob", "Cat", "David"])
df1.join(df2)output:
Age City Alice 25 HK Bob 30 Tokyo Cat 22 Sydney Peter 40 NaN
Example 3:索引不匹配時 join — Bob 補上 NaN #
#When index not match
import pandas as pd
df1 = pd.DataFrame({
"Age": [25,30]
}, index=["Alice", "Bob"])
df2 = pd.DataFrame({
"City": ["HK"]
}, index=["Alice"])
df1.join(df2)output:
Age City Alice 25 HK Bob 30 NaN
Example 4:一次 join 多個 DataFrame — 傳入 list #
import pandas as pd
df1 = pd.DataFrame({
"Age": [25,30]
}, index=["Alice", "Bob"])
df2 = pd.DataFrame({
"City": ["HK", "Taiwan"]
}, index=["Alice", "Bob"])
df3 = pd.DataFrame({
"Score": [90, 50]
}, index=["Alice", "Bob"])
df1.join([df2, df3])output:
Age City Score Alice 25 HK 90 Bob 30 Taiwan 50
Example 5:how="inner" join — 先將索引轉為小寫以匹配 #
names = pd.DataFrame({"age":[30,40]}, index=["alice","ben"])
cities = pd.DataFrame({"city":["HK","Tokyo"]}, index=["Alice","Ben"])
names.index = names.index.str.lower()
cities.index = cities.index.str.lower()
print(names.join(cities, how="inner"))output:
age city alice 30 HK ben 40 Tokyo
