1. 程式人生 > >Python 筆記 #17# Pandas: Merge

Python 筆記 #17# Pandas: Merge

ram 1.8 frame nor pen tar right http 1.2

10 Minutes to pandas

Concat

df = pd.DataFrame(np.random.randn(10, 4))
print(df)
# break it into pieces
pieces = [df[:3], df[3:7], df[7:]]
print(pd.concat(pieces))
#           0         1         2         3
# 0  0.879526 -1.417311 -1.309299  0.287933
# 1 -1.194092  1.237536 -0.375177 -0.622846
#
2 1.449524 1.732103 1.866323 0.327194 # 3 -0.028595 1.047751 0.629286 -0.611354 # 4 -1.237406 0.878287 1.407587 -1.637072 # 5 0.536248 1.172208 0.405543 0.245162 # 6 0.166374 1.185840 0.132388 -0.832135 # 7 0.750722 -1.188307 1.306327 1.564907 # 8 -0.755132 -1.538270 -0.173119 1.341313 # 9 -0.572171 1.808220 0.688190 -0.672612
# 0 1 2 3 # 0 0.879526 -1.417311 -1.309299 0.287933 # 1 -1.194092 1.237536 -0.375177 -0.622846 # 2 1.449524 1.732103 1.866323 0.327194 # 3 -0.028595 1.047751 0.629286 -0.611354 # 4 -1.237406 0.878287 1.407587 -1.637072 # 5 0.536248 1.172208 0.405543 0.245162 # 6 0.166374 1.185840 0.132388 -0.832135
# 7 0.750722 -1.188307 1.306327 1.564907 # 8 -0.755132 -1.538270 -0.173119 1.341313 # 9 -0.572171 1.808220 0.688190 -0.672612

Join

類似 sql 裏的 join (聯表)

left = pd.DataFrame({key: [foo, foo], lval: [1, 2]})
right = pd.DataFrame({key: [foo, foo], rval: [4, 5]})
print(left)
print(right)
print(pd.merge(left, right, on=key))
#    key  lval
# 0  foo     1
# 1  foo     2
#    key  rval
# 0  foo     4
# 1  foo     5
#    key  lval  rval
# 0  foo     1     4
# 1  foo     1     5
# 2  foo     2     4
# 3  foo     2     5

Merge

df = pd.DataFrame(np.random.randn(8, 4), columns=[A,B,C,D])
print(df)
s = df.iloc[3]
print(s)
df.append(s, ignore_index=True)
print(df)
#           A         B         C         D
# 0 -1.744799 -0.745689 -0.066827 -0.993191
# 1  0.843984  0.902578  0.845040  1.336861
# 2  0.865214  1.151313  0.277192 -0.711557
# 3  0.917065 -0.948935  0.110977  0.047466
# 4 -1.309586  0.539592  1.956684 -0.117199
# 5 -0.431144  0.884499 -0.828626 -0.506894
# 6 -1.263993 -0.826366  1.426688 -0.434647
# 7 -0.567870 -0.086037  2.166162 -0.396294
# /
# A    0.917065
# B   -0.948935
# C    0.110977
# D    0.047466
# Name: 3, dtype: float64
# /
#           A         B         C         D
# 0 -1.744799 -0.745689 -0.066827 -0.993191
# 1  0.843984  0.902578  0.845040  1.336861
# 2  0.865214  1.151313  0.277192 -0.711557
# 3  0.917065 -0.948935  0.110977  0.047466
# 4 -1.309586  0.539592  1.956684 -0.117199
# 5 -0.431144  0.884499 -0.828626 -0.506894
# 6 -1.263993 -0.826366  1.426688 -0.434647
# 7 -0.567870 -0.086037  2.166162 -0.396294

Python 筆記 #17# Pandas: Merge