piper.verbs.relocate¶
-
piper.verbs.relocate(df: pandas.core.frame.DataFrame, column: Optional[Union[str, list]] = None, loc: str = 'last', ref_column: Optional[str] = None, index: bool = False) → pandas.core.frame.DataFrame[source]¶ move column(s) in a dataframe
Based on the corresponding R function - relocate
Examples
%%piper sample_matrix() >> relocate('e', 'before', 'b') >> select('-c') >> where("a < 20 and b > 1") >> order_by(['-d']) >> head(5, tablefmt='plain') a e b d 0 15 8 9 25 1 8 15 26 5 2 5 -7 5 -9
%%piper sample_sales() >> select(('location', 'target_profit')) >> pd.DataFrame.set_index(['location', 'product']) >> head(tablefmt='plain') month target_sales target_profit ('London', 'Beachwear') 2021-01-01 00:00:00 31749 1905 ('London', 'Beachwear') 2021-01-01 00:00:00 37833 6053 ('London', 'Jeans') 2021-01-01 00:00:00 29485 4128 ('London', 'Jeans') 2021-01-01 00:00:00 37524 3752 %%piper sample_sales() >> select(('location', 'target_profit')) >> pd.DataFrame.set_index(['location', 'product']) >> relocate(column='location', loc='after', ref_column='product', index=True) >> head(tablefmt='plain') month target_sales target_profit ('Beachwear', 'London') 2021-01-01 00:00:00 31749 1905 ('Beachwear', 'London') 2021-01-01 00:00:00 37833 6053 ('Jeans', 'London') 2021-01-01 00:00:00 29485 4128 ('Jeans', 'London') 2021-01-01 00:00:00 37524 3752
NOTE If you omit the keyword parameters, it probably ‘reads’ better ;) >> relocate(location’, ‘after’, ‘product’, index=True)
- Parameters
df – dataframe
column – column name(s) to be moved
loc – default -‘last’. The relative location to move the column(s) to. Valid values are: ‘first’, ‘last’, ‘before’, ‘after’.
ref_column – Default - None. Reference column
index – default is False (column). If True, then the column(s) being moved are considered to be row indexes.
- Returns
- Return type
A pandas dataframe