【问题标题】:Creating new column with values that depends on other columns使用依赖于其他列的值创建新列
【发布时间】:2023-01-09 17:44:12
【问题描述】:

我有一个熊猫数据框,其中包含逐场篮球数据。

我想查看玩家错过投掷的游戏事件列,如果他错过了投掷,我想添加一个新列“Missed throw”,并在此行中将值设置为 0 到 1。 如果他错过了下一次投掷,我想将列中的值从 1 增加到 2 等。

这是我的数据框

import pandas as pd

url = 'https://www.basketball-reference.com/boxscores/pbp/200911060GSW.html'
dfs = pd.read_html(url)

df = dfs[0] 
df.columns = df.columns.droplevel() # drops the "1st Q" Multilevel header of the dataframe

df.rename(columns={'Unnamed: 2_level_1': 'PM1', 'Unnamed: 4_level_1': 'PM2'}, inplace=True)

df

然后我做了咖喱的一个子集,因为我专注于他的行为。

df_curry = df.loc[df["Golden State"].str.contains("Curry", na=False)]
df_curry`

现在我尝试将命中而不是命中抛出插入到新列中以稍后计算报价但我总是收到错误“str”对象没有属性“str”。 也许有人可以帮助我或给我另一种方法

# Calculating Hit Rate

field_throws_missed = 0
field_throws_hit = 0`

# Creating the new Columns
df_curry["Field Goals Hit"] = 0
df_curry["Field Goals Missed"] = 0
df_curry["Field Goals Percentage"] = 0`


for row in range(len(df_curry["Golden State"])):
  if df_curry.iloc[row]["Golden State"].str.contains("misses 2|misses 3"): 
    field_throws_missed += 1
    df_curry.iloc[row]["Field Goals Missed"] = field_throws_missed
  elif df_curry.iloc[row]["Golden State"].str.contains("makes 2|makes 3"): 
    field_throws_hit += 1
    df_curry.iloc[row]["Field Goals Hit"] = field_throws_hit`

【问题讨论】:

    标签: python pandas data-science


    【解决方案1】:

    这里不需要循环,对于计数Trues 值使用Series.cumsum 的累积和:

    df_curry = df.loc[df["Golden State"].str.contains("Curry", na=False)].copy()
    
    df_curry["Field Goals Hit"] = df_curry["Golden State"].str.contains("misses 2|misses 3").cumsum()
    df_curry["Field Goals Missed"] = df_curry["Golden State"].str.contains("makes 2|makes 3").cumsum()
    

    【讨论】:

    • 感谢您的快速回复!问题是整场比赛他投丢了四次。代码正确地表明了这一点。但它显示每行有四次投掷,在他没有投掷之前的行中也显示了四次投掷。而且我只想在他也击中或未击中时才在列中具有值,该列仅在那时更新为 +1。
    • @nick.s99 - Field Goals Hit 列中的数字预期输出是什么?
    • @nick.s99 - 也许需要df_curry["Field Goals Hit"] = df_curry["Golden State"].str.contains("misses 2|misses 3").cumsum()
    • 他只在第 250 行投了一个球。我希望“投篮命中率”列的前 249 行在命中前为 0,然后在此之后我希望行为 1。
    • 哦,cumsum 确实有效!万分感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2023-03-23
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多