Edit: 2022NOV21
How do we chain df.col.str.split()
since this returns the split columns if expand = True
I am trying to split a column after performing .melt()
. If I use assign I end up using the original column and the melted column actually does not even exist.
df = pd.DataFrame().from_dict({
'id' : [1,2,3,4],
'2022_amt' : [10.1,20.2,30.3, 40.4],
'2022_qty' : [10,20,30,40]
})
df = (
df
.melt(
id_vars=['id'],
value_vars=['2022_amt', '2022_qty'],
var_name='fy',
value_name='num'
)
# can i chain any pd.Series.str.[METHOD] here
# .assign(
# year=df.fy.str.split('_', expand=True)[0],
# t=df.fy.str.split('_', expand=True)[1]
# )
)
# i can add the two columns in this way but can we use chain to expand dataframe df
df[['year', 't']] = df.fy.str.split('_', expand=True)
df = df.drop(columns = ['fy'])