import numpy as np
import pandas as pd
轴向堆叠练习
两个 Data Frame 对象, dfl 的列索弓 l 为[ 0 , 1 , 2 , 3 ] ,行索引为0- 5 , df2 的列索引为[2,3,4 , 5 ] ,行索引为0-4 ,数据随机整数,范围 3 一 9
df1 = pd.DataFrame(np.random.randint(3,9,(6,4)))
df1
| 0 | 1 | 2 | 3 |
---|
0 | 7 | 5 | 5 | 5 |
---|
1 | 6 | 6 | 3 | 3 |
---|
2 | 7 | 6 | 6 | 7 |
---|
3 | 5 | 3 | 3 | 5 |
---|
4 | 8 | 7 | 3 | 8 |
---|
5 | 4 | 5 | 6 | 5 |
---|
df2 = pd.DataFrame(np.random.randint(3,9,(5,4)),columns=[2,3,4,5])
df2
| 2 | 3 | 4 | 5 |
---|
0 | 6 | 5 | 4 | 6 |
---|
1 | 8 | 6 | 4 | 5 |
---|
2 | 3 | 5 | 3 | 6 |
---|
3 | 3 | 6 | 3 | 5 |
---|
4 | 4 | 8 | 5 | 7 |
---|
1 、横向堆叠外连接上述两个 DataF ra me 对象
pd.concat([df1,df2],join='outer',axis=1)
| 0 | 1 | 2 | 3 | 2 | 3 | 4 | 5 |
---|
0 | 7 | 5 | 5 | 5 | 6.0 | 5.0 | 4.0 | 6.0 |
---|
1 | 6 | 6 | 3 | 3 | 8.0 | 6.0 | 4.0 | 5.0 |
---|
2 | 7 | 6 | 6 | 7 | 3.0 | 5.0 | 3.0 | 6.0 |
---|
3 | 5 | 3 | 3 | 5 | 3.0 | 6.0 | 3.0 | 5.0 |
---|
4 | 8 | 7 | 3 | 8 | 4.0 | 8.0 | 5.0 | 7.0 |
---|
5 | 4 | 5 | 6 | 5 | NaN | NaN | NaN | NaN |
---|
2 、纵向堆叠内连接上述两个DataFrame对象,重置堆叠的索引
pd.concat([df1,df2],join='inner',axis=0)
| 2 | 3 |
---|
0 | 5 | 5 |
---|
1 | 3 | 3 |
---|
2 | 6 | 7 |
---|
3 | 3 | 5 |
---|
4 | 3 | 8 |
---|
5 | 6 | 5 |
---|
0 | 6 | 5 |
---|
1 | 8 | 6 |
---|
2 | 3 | 5 |
---|
3 | 3 | 6 |
---|
4 | 4 | 8 |
---|
concat文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html?highlight=concat#