【问题标题】:Pandas: iterate over a row and adding the value to an empty columnPandas:遍历一行并将值添加到空列
【发布时间】:2018-12-31 11:24:11
【问题描述】:

您好,我想遍历 CPB% 行并将计算添加到名为“Proba”的相关列中。我的数据框如下所示:

到目前为止我尝试过的看起来是这样的:

bins = np.linspace(0, 1, num=100)
dCPB = df['CPB%']
df['binnedB'] = pd.cut(dCPB, bins)
dfnew = pd.DataFrame(pd.cut(df['CPB%'], bins=bins).value_counts()).sort_index(ascending = True)
dfnew['binned'] = dfnew.index

total = dfnew['CPB%'].sum()
idx = total

for index,row in dfnew.iterrows():
  idx = idx - row['CPB%']
  row['Proba'] = float(idx) / float(total)

但是我的迭代没有更新我的空列 Proba,知道为什么吗?谢谢!

【问题讨论】:

  • 请将您的数据框粘贴为文本而不是图像

标签: python pandas dataframe series


【解决方案1】:

我认为问题在于,您将结果分配回row,它不会存储在任何地方。相反,您可以这样做:

proba = []

for index, row in dfnew.iterrows():
    idx = idx - row['CPB%']
    proba.append(float(idx) / float(total))

dfnew['Proba'] = proba

但是,这不是最好的方法,您可以使用 .applyaxis=1 对数据框进行逐行计算。

【讨论】:

  • 是的,谢谢,但我还有另一个问题错误:'无法连接类型为“”的对象;只有 pd.Series
  • 您需要在这里使用proba = [] 而不是proba = pd.Series()。但是当你可以使用cumsum时,这并不是真的必要。
【解决方案2】:

您可以使用pd.Series.cumsum 进行迭代推演:

total = dfnew['CPB%'].sum()
dfnew['Proba'] = 1 - df['CPB%'].cumsum() / total

对于 Pandas,您应该考虑向量化算法,这通常涉及按列操作,而不是按行 for 循环。这是一个完整的演示:

df = pd.DataFrame({'A': list(range(1, 7))})

def jpp(df):
    total = df['A'].sum()
    df['Proba'] = 1 - df['A'].cumsum() / total
    return df

def yolo(df):
    total = df['A'].sum()
    idx = total

    proba = []
    for index, row in df.iterrows():
        idx = idx - row['A']
        proba.append(float(idx) / float(total))

    df['Proba'] = proba
    return df

# check results are the same
assert df.pipe(jpp).equals(df.pipe(yolo))

%timeit df.pipe(jpp)   # 691 µs
%timeit df.pipe(yolo)  # 840 µs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2019-10-23
    • 2013-03-09
    • 2021-02-13
    • 2014-07-16
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多