在Python中,将行值移动到新列包含特定字符串

2024-05-15 00:36:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在重组数据框架。示例数据框如下所示:

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]

我想创建一个新列,其中只包含诸如“Won”、“Acc”和“Suc”之类的字符串。预期的数据帧如下所示:

enter image description here

我可以试着解决这个问题吗


Tags: 数据框架示例dataframedfdefstatsback
3条回答

使用str.containsnp.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]

解决方案:

# 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'])

输出:

         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]

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]

相关问题 更多 >

    热门问题