likes
comments
collection
share

在Python中使用rbind (等同于R)

作者站长头像
站长
· 阅读数 5

R中的rbind函数,即_row-bind_的缩写,可以用来将数据帧按其行数组合在一起。

我们可以使用pandas的concat()函数来执行Python中的同等功能。

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

下面的例子展示了如何在实践中使用这个函数。

例1:在Python中使用rbind,列数相等

假设我们有以下两个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

我们可以使用**concat()**函数来快速地将这两个 DataFrames 按行绑定在一起。

#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

请注意,我们也可以使用**reset_index()**来重置新的DataFrame的索引值。

#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

例2:在Python中使用不等列的rbind

我们也可以使用**concat()**函数将两个列数不相等的DataFrame行绑定在一起,任何缺失的值都将简单地填充为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