current position:Home>Using rbind in python (equivalent to R)

Using rbind in python (equivalent to R)

2022-01-30 11:56:30 Stone sword


R Medium rbind function , namely _row-bind_ Abbreviation , It can be used to combine data frames according to their number of rows .

We can use pandas Of concat() Function to execute Python Equivalent functions in .

df3 = pd.concat([df1, df2])

 Copy code 

The following example shows how to use this function in practice .

example 1: stay Python Use in rbind, The number of columns is equal

Suppose we have the following two pandas DataFrames.

import pandas as pd

#define DataFrames
df1 = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E'],
                    'points': [99, 91, 104, 88, 108]})

print(df1)

  team  points
0    A      99
1    B      91
2    C     104
3    D      88
4    E     108

df2 = pd.DataFrame({'assists': ['F', 'G', 'H', 'I', 'J'],
                    'rebounds': [91, 88, 85, 87, 95]})

print(df2)

  team  points
0    F      91
1    G      88
2    H      85
3    I      87
4    J      95

 Copy code 

We can use **concat()** Function to quickly combine these two DataFrames Bound together by line .

#row-bind two DataFrames
df3 = pd.concat([df1, df2])

#view resulting DataFrame
df3

	team	points
0	A	99
1	B	91
2	C	104
3	D	88
4	E	108
0	F	91
1	G	88
2	H	85
3	I	87
4	J	95

 Copy code 

Please note that , We can also use **reset_index()** To reset the new DataFrame The index of the value .

#row-bind two DataFrames and reset index values
df3 = pd.concat([df1, df2]).reset_index(drop=True)

#view resulting DataFrame
df3

	team	points
0	A	99
1	B	91
2	C	104
3	D	88
4	E	108
5	F	91
6	G	88
7	H	85
8	I	87
9	J	95
 Copy code 

example 2: stay Python Using unequal columns in rbind

We can also use **concat()** The function returns two columns with unequal numbers DataFrame The rows are bound together , Any missing values will simply be populated with NaN.

import pandas as pd

#define DataFrames
df1 = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E'],
                    'points': [99, 91, 104, 88, 108]})

df2 = pd.DataFrame({'team': ['F', 'G', 'H', 'I', 'J'],
                    'points': [91, 88, 85, 87, 95],
                    'rebounds': [24, 27, 27, 30, 35]})

#row-bind two DataFrames
df3 = pd.concat([df1, df2]).reset_index(drop=True)

#view resulting DataFrame
df3

	team	points	rebounds
0	A	99	NaN
1	B	91	NaN
2	C	104	NaN
3	D	88	NaN
4	E	108	NaN
5	F	91	24.0
6	G	88	27.0
7	H	85	27.0
8	I	87	30.0
9	J	95	35.0
 Copy code 

copyright notice
author[Stone sword],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301156278008.html

Random recommended