如何解决使用 Python Pandas 中上一行的数据在列中创建行值
我正在尝试创建一个新列,其中第一行中的值为 0,从第二行开始,它应该进行如下所述的计算
ColumnA[This row] = (ColumnA[Last row] * 13 + ColumnB[This row])/14
我正在使用 python pandas shift 函数,但它似乎没有产生预期的结果。
test = np.array([ 1,5,3,20,2,6,9,8,7])
test = pd.DataFrame(test,columns = ['ABC'])
test.loc[test['ABC'] == 1,'a'] = 0
test['a'] = (test['a'].shift()*13 + test['ABC'])/14
我正在尝试创建一个看起来像这样的列
ABC | 一个 |
---|---|
1 | 0 |
5 | 0.3571 |
3 | 0.5459 |
20 | 1.9355 |
2 | 1.9401 |
6 | 2.2301 |
9 | 2.7137 |
8 | 3.0913 |
7 | 3.3705 |
但实际上我通过运行上面的代码得到的是这个
ABC | 一个 |
---|---|
1 | 南 |
2 | 0 |
3 | 南 |
4 | 南 |
5 | 南 |
6 | 南 |
7 | 南 |
8 | 南 |
9 | 南 |
解决方法
test = np.array([ 1,2,3,4,5,6,7,8,9])
test = pd.DataFrame(test,columns = ['ABC'])
test["res"] = test["ABC"]
test.iloc[0]['res'] = 0 # Initialize the first row as 0
test["res"] = test.res + test.res.shift()
test["res"] = test.res.fillna(0).astype(int) # test.res.shift() introduces a nan and we replace it with a 0 and convert the column data type to int
,
试试:
test["a"] = (test["ABC"].shift().cumsum() + test["ABC"].shift()).fillna(0)
print(test)
打印:
ABC a
0 1 0.0
1 2 2.0
2 3 5.0
3 4 9.0
4 5 14.0
5 6 20.0
6 7 27.0
7 8 35.0
8 9 44.0
,
让我们试试 for 循环
import pandas as pd
df = pd.DataFrame({'ABC': [1,20,9,7]})
lst = [0]
res = 0
for i,row in df.iloc[1:].iterrows():
res = ((res * 13) + row['ABC']) / 14
lst.append(res)
df['a'] = pd.Series(lst)
print(df)
输出:
ABC a
0 1 0.000000
1 5 0.357143
2 3 0.545918
3 20 1.935496
4 2 1.940103
5 6 2.230096
6 9 2.713660
7 8 3.091256
8 7 3.370452
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。