Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving row values contains specific string to new column in Python

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:

enter image description here

What can I try to resolve this?

like image 566
Zephyr Avatar asked Jun 16 '26 16:06

Zephyr


2 Answers

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]
like image 196
BENY Avatar answered Jun 18 '26 07:06

BENY


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]
like image 36
Quang Hoang Avatar answered Jun 18 '26 07:06

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!