I am restructuring the data frame. The sample data frame is as follow:
df = pd.DataFrame()
df ['Stats'] = ['Def duels', 'Def duels Won','Back passes', 'Back passes[Acc]','Dribbles', 'Dribbles[Suc]']
df ['Value'] = [5,2.5,60,55,5,2]
I want to create a new column which only contains the string such as 'Won','Acc' and 'Suc'. The expected data frame is as follow:

What can I try to resolve this?
IIUC
s=df.Stats.str.contains('Won|Acc|Suc')
df['New']=df.Stats.where(s,'')
df.Stats=df.Stats.mask(s,'')
df
Stats Value New
0 Def duels 5.0
1 2.5 Def duels Won
2 Back passes 60.0
3 55.0 Back passes[Acc]
4 Dribbles 5.0
5 2.0 Dribbles[Suc]
A solution:
# initialize Stats1 with empty strings
df['Stats1'] = ''
# copy values from `Stats`
df.iloc[1::2,-1] = df['Stats']
# replace the copied values with empty strings
df['Stats'] = np.where(df['Stats1'].ne(''), '', df['Stats'])
Output:
Stats Value Stats1
0 Def duels 5.0
1 2.5 Def duels Won
2 Back passes 60.0
3 55.0 Back passes[Acc]
4 Dribbles 5.0
5 2.0 Dribbles[Suc]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With