Friday, August 26, 2022

How to Merge Two Pandas DataFrames on Index

Функция join() по умолчанию выполняет левое соединение, поэтому каждый из индексов в первом кадре данных сохраняется.

Функция merge() по умолчанию выполняет внутреннее соединение, поэтому сохраняются только те индексы, которые появляются в обоих кадрах данных.

Функция concat() по умолчанию выполняет внешнее соединение, поэтому сохраняется каждое значение индекса из каждого кадра данных.

(.env) boris@boris-All-Series:~/VALUEPY$ cat mergePandas.py

import pandas as pd

#create first DataFrame

df1 = pd.DataFrame({'rating': [90, 85, 82, 88, 94, 90, 76, 75],

                   'points': [25, 20, 14, 16, 27, 20, 12, 15]},

                   index=list('abcdefgh'))

print(df1)

#create second DataFrame 

df2 = pd.DataFrame({'assists': [5, 7, 7, 8, 5, 7],

                   'rebounds': [11, 8, 10, 6, 6, 9]},

                   index=list('acdgmn'))           

print(df2)

# Merge DataFrames Using Join

print("Merge DataFrames Using Join")

print(df1.join(df2))

# Merge DataFrames Using Merge

print("Merge DataFrames Using Merge")

print(pd.merge(df1, df2, left_index=True, right_index=True))

# Merge DataFrames Using Concat

print("Merge DataFrames Using Concat")

print(pd.concat([df1, df2], axis=1))


(.env) boris@boris-All-Series:~/VALUEPY$ python3 mergePandas.py

   rating  points

a      90      25

b      85      20

c      82      14

d      88      16

e      94      27

f      90      20

g      76      12

h      75      15

   assists  rebounds

a        5        11

c        7         8

d        7        10

g        8         6

m        5         6

n        7         9

Merge DataFrames Using Join

   rating  points  assists  rebounds

a      90      25      5.0      11.0

b      85      20      NaN       NaN

c      82      14      7.0       8.0

d      88      16      7.0      10.0

e      94      27      NaN       NaN

f      90      20      NaN       NaN

g      76      12      8.0       6.0

h      75      15      NaN       NaN

Merge DataFrames Using Merge

   rating  points  assists  rebounds

a      90      25        5        11

c      82      14        7         8

d      88      16        7        10

g      76      12        8         6

Merge DataFrames Using Concat

   rating  points  assists  rebounds

a    90.0    25.0      5.0      11.0

b    85.0    20.0      NaN       NaN

c    82.0    14.0      7.0       8.0

d    88.0    16.0      7.0      10.0

e    94.0    27.0      NaN       NaN

f    90.0    20.0      NaN       NaN

g    76.0    12.0      8.0       6.0

h    75.0    15.0      NaN       NaN

m     NaN     NaN      5.0       6.0

n     NaN     NaN      7.0       9.0































No comments:

Post a Comment