简体   繁体   English

根据 Pandas 中的条件将列值加一

[英]Increase column value by one based on condition in Pandas

I created a script that scrapes NBA play-by-play data and organizes it into a pandas dataframe.我创建了一个脚本,它会抓取 NBA 的比赛数据并将其组织成 pandas dataframe。 At the end of each quarter and the end of the game, the below values are shown in the 'Detail' column:在每节结束和比赛结束时,“详细信息”列中显示以下值:

    Detail
End of the 1st Quarter  
End of the 2nd Quarter  
End of the 3rd Quarter  
End of the 4th Quarter  
End of Game 

Is there a way to create a 'Quarter' column that starts with the number 1, then increases by 1 after the end of each quarter by using the 'Detail' Column?有没有办法创建一个以数字 1 开头的“季度”列,然后使用“详细信息”列在每个季度结束后增加 1? For example:例如:

Detail           Quarter
Shot by...          1
Rebound...          1
End of 1st Quarter  1
Pass to...          2

use a boolean with cumsum and bfill使用带有cumsum和 bfill 的bfill

import numpy as np
df['Quarter'] = np.where(
              df['Detail'].str.contains('Quarter'),
                             df['Detail'].str.contains('Quarter').cumsum(), 
                             np.nan
                       )

df['Quarter'] = df['Quarter'].bfill()

print(df)
   Detail               Quarter
0  Shot by...              1.0
1  Rebound...              1.0
2  End of 1st Quarter      1.0
3  Pass to...              2.0
4  Shot by...              2.0
5  Rebound...              2.0
6  End of 2nd Quarter      2.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据 pandas 中的条件将一列值分配给另一列 - assign one column value to another column based on condition in pandas 根据条件将值从一列复制到另一列(使用熊猫) - Copy value from one column to another based on condition (using pandas) 如何根据 python dataframe 中的特定条件将每个单元格值增加一个特定列 - How to increase a particular column each cell value by one, based on a certain condition in python dataframe 熊猫根据条件将一列映射到另一列 - Pandas map one column to another based on condition 根据一列的条件和熊猫中另一列的值创建新列 - Create new column based on condition from one column and the value from another column in pandas SettingWithCopyWarning Pandas 根据条件在列中设置值 - SettingWithCopyWarning Pandas setting value in column based on condition pandas 根据条件将值添加到新列 - pandas add value to new column based on condition pandas - 有没有办法根据条件将值从一个 dataframe 列复制到另一个列? - pandas - Is there a way to copy a value from one dataframe column to another based on a condition? Pandas 根据另一列中的条件计算一列中的计数 - Pandas count number in one column based off a condition in a different column Pandas 根据其他列的条件添加列 - Pandas add column with value based on condition based on other columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM