繁体   English   中英

如何使用pandas数据帧计算列的x百分比

[英]How to calculate x percentage of column using pandas dataframe

我试图使用pd.Series计算列值的x百分比。 我收到NoneType的错误。 不确定我做错了什么。

def PctMA(self, df, pct):
    pctName = 'PCT' + str(pct)
    pctDecimal = float(pct/100)
    pctCalulated = pd.Series((df['value'] - (df['value'] * pctDecimal)), name = pctName)
    df = df.join(pctCalulated)
    return df
I get the below error when I execute the code.

    pctCalulated = pd.Series((df['value'] - (df['value'] * pctDecimal)), name = pctName)
TypeError: 'NoneType' object has no attribute '__getitem__'

下面是预期结果,其中Pct1生成为1%的值列。

index   value   pct1
1   2476    2451.24
2   2475    2450.25
3   2486    2461.14
4   2536    2510.64
5   2453    2428.47
6   2486    2461.14
7   2648    2621.52
8   2563    2537.37
9   2756    2728.44

也许错误不是在函数中而是在输入中,因为我刚刚使用了您的代码并且它正在工作:

def PctMA(df, pct):
    pctName = 'PCT' + str(pct)
    pctDecimal = float(pct/100)
    pctCalulated = pd.Series((df['value'] - (df['value'] * pctDecimal)), name = pctName)
    df = df.join(pctCalulated)

    return df

df = pd.DataFrame({'value': [2476,2476,2486,2536]})
df_1 = PctMA(df, pct)
df_1

在此输入图像描述

提供更多细节会更好。

我用最小的更改执行你的代码(只是用1%的值映射)。 下面是我执行的代码,它工作得很好。 输入问题。

在此输入图像描述

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM