How to stack two series vertically and horizontally in pandas
pandas’s library allows two series to be stacked as vertical and horizontal using a built-in command called concat(). This action is usually performed to create a dataframe from two series.
Syntax
pandas.concat(objs, axis, join, ignore_index,keys, levels, names, verify_integrity,sort, copy)
Parameters
-
objs: This is the mapping of Dataframe or Series objects. If we pass the mapping, their keys will be sorted and used in argumentkeys. Ifkeysare already passed as an argument, then those passed values will be used. AnyNullobjects will be dropped. -
axis: This is the axis along which we want to stack our series. The default is0.0represents Horizontal.1represents Vertical. -
join: This parameter tells us how to handle indexes on other axes. It has two types:innerandouter, and the default isouter. -
ignore_index(bool): This tells whether or not to ignore index values. The default isFalse. -
keys(sequence): This tells us the sequence of the identifier in resultant indices. The default isNone. -
levels(list of sequences): This tells us the levels for constructing Multi-index. The default isNone. -
names(list): This tells us the names of levels in resultant index. The default isNone. -
verify_integrity(bool): This checks duplicates in the resultant axis. The default isFalse. -
sort(bool): This sorts non-concatenation axis. It only works withouterjoin, and the default isFalse. -
copy(bool): This tells whether or not to stop copying unnecessary data. The default isTrue.
Return values
-
Series: If
objscontains all series. -
Dataframe: If
objscontains at least one Dataframe.
Vertical stacking
Using concat()
#importing pandas libraryimport pandas as pd#initializing two pandas seriesseries1 = pd.Series(range(len('educative')))series2 = pd.Series(list('educative'))#vertical stack with axis = 0 as parameterprint(pd.concat([series1, series2], axis = 0))
Using append()
#importing pandas libraryimport pandas as pd#initializing two pandas seriesseries1 = pd.Series(range(len('educative')))series2 = pd.Series(list('educative'))#Vertical stack using appendprint(series1.append(series2))
Horizontal stacking
#importing pandas libraryimport pandas as pd#initializing two pandas seriesseries1 = pd.Series(range(len('educative')))series2 = pd.Series(list('educative'))#Horizontal stack with axis = 1 as parameterprint(pd.concat([series1, series2], axis = 1))