pd.concat
method in Pandas
appends either rows or columns of Dataframes, if axis=0
is given in
pd.conact
rows would be appended
and with axis=1
, columns would be appended.
Lets take an example to understand pd.concat
import pandas as pd
df1 = pd.DataFrame({'col1': ['one', 'two', 'one', 'test', 'three','test2'],
'col2': ['aaa', 'bbb', 'ccc', 'eec', 'gggg', 'ggkk'],
'col3': [11, 23, 34, 46, 56, 66]})
df2 = pd.DataFrame({'col1': [56, 78, 78 , 89],
'col2': ['aaa', 'bbb', 'ccc', 'ddd'],
'col3': [11, 23, 34, 46]})
print(df1)
print(df2)
col1 col2 col3
0 one aaa 11
1 two bbb 23
2 one ccc 34
3 test eec 46
4 three gggg 56
5 test2 ggkk 66
col1 col2 col3
0 56 aaa 11
1 78 bbb 23
2 78 ccc 34
3 89 ddd 46
pd.concat
along axis=0
df3 = pd.concat([df1, df2])
print("Concat along axis=0, i.e increased number of rows ")
print(df3)
Concat along axis=0, i.e increased number of rows
col1 col2 col3
0 one aaa 11
1 two bbb 23
2 one ccc 34
3 test eec 46
4 three gggg 56
5 test2 ggkk 66
0 56 aaa 11
1 78 bbb 23
2 78 ccc 34
3 89 ddd 46
pd.concat
along axis=1
df4 = pd.concat([df1, df2], axis=1)
print("Concat along axis=1, i.e increased number of Columns ")
print(df4)
Concat along axis=1, i.e increased number of Columns
col1 col2 col3 col1 col2 col3
0 one aaa 11 56.0 aaa 11.0
1 two bbb 23 78.0 bbb 23.0
2 one ccc 34 78.0 ccc 34.0
3 test eec 46 89.0 ddd 46.0
4 three gggg 56 NaN NaN NaN
5 test2 ggkk 66 NaN NaN NaN
Similar Articles