[英]How to calculate x percentage of column using pandas dataframe
I am trying to calculate x percentage of column value using pd.Series. 我试图使用pd.Series计算列值的x百分比。 I am getting error of NoneType. 我收到NoneType的错误。 Not really sure what I'm doing wrong. 不确定我做错了什么。
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__'
Below is the Expected results with Pct1 being generated as 1% column of value. 下面是预期结果,其中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
Maybe the error is not in the function but in the input, as I just used your code and it is working: 也许错误不是在函数中而是在输入中,因为我刚刚使用了您的代码并且它正在工作:
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
It is better to give more details. 提供更多细节会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.