1. 程式人生 > >python3 join函式使用總結

python3 join函式使用總結

1、字串連線

list1 = ['a','b']
str1 = ''.join(list1)
print(str1)
結果:ab

2,pd.DataFrame.join連線

import pandas as pd
other = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],
            'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
caller= pd.DataFrame({'key': ['K0', 'K1', 'K2'],
                    'B'
: ['B0', 'B1', 'B2']}) data1 = other.join(caller,lsuffix='_left')#預設左連線,按索引連線,左邊資料大 print(data1) data2 = caller.join(other,lsuffix='_left')#按左邊的索引連線,左邊資料少,自動捨棄右邊剩餘資料 print(data2) data3=caller.set_index('key').join(other.set_index('key'))#左邊小。‘key'當索引連線,右邊資料多餘的自動捨棄 print(data3) data4 = other.set_index('key'
).join(caller.set_index('key')) print(data4)#左邊資料大,’key‘當索引,右邊數數不夠的,自動補充NaN # 按某一列連線 data5 = other.join(caller.set_index('key'),on='key') print(data5)#'key'設為共同的列,按左邊的key顯示資料 data6 = caller.join(other.set_index('key'),on='key') print(data6)#'key'設為共同的列,按左邊的key顯示資料 data7 = caller.join(other.set_index('key'
),on='key',how='right') print(data7)#'key'設為共同的列,按右邊的key顯示資料

結果:
1,
A key_left B key
0 A0 K0 B0 K0
1 A1 K1 B1 K1
2 A2 K2 B2 K2
3 A3 K3 NaN NaN
4 A4 K4 NaN NaN
5 A5 K5 NaN NaN

2,
B key_left A key
0 B0 K0 A0 K0
1 B1 K1 A1 K1
2 B2 K2 A2 K2

3,
B A
key
K0 B0 A0
K1 B1 A1
K2 B2 A2

4,
A B
key
K0 A0 B0
K1 A1 B1
K2 A2 B2
K3 A3 NaN
K4 A4 NaN
K5 A5 NaN

5,
A key B
0 A0 K0 B0
1 A1 K1 B1
2 A2 K2 B2
3 A3 K3 NaN
4 A4 K4 NaN
5 A5 K5 NaN

6,
B key A
0 B0 K0 A0
1 B1 K1 A1
2 B2 K2 A2

7,
B key A
0 B0 K0 A0
1 B1 K1 A1
2 B2 K2 A2
2 NaN K3 A3
2 NaN K4 A4
2 NaN K5 A5