[英]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'.我想创建一个新列,它只包含诸如“Won”、“Acc”和“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]
using str.contains
with np.where
使用
str.contains
和np.where
df['stat1'] = np.where(df['Stats'].str.contains('won|acc|suc',case=False),df['Stats'],'')
df['Stats'] = np.where(df['Stats'].str.contains('won|acc|suc',case=False),'',df['Stats'])
print(df)
Stats Value stat1
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.