'How to sum in a for loop in pandas DataFrame
I am the beginner in pandas and am struggling with a for loop.
I loaded the following excel file to pandas:
x=pd.read_excel('BTC.xlsx',)
x
Here is what I get:
BTC obtained
0 0.00567
1 0.00054
2 0.00230
I want to iterate the numbers using a for loop:
n=0
for v in x.iteritems():
n+=v
print(n)
When I run this, I always get the following error:
TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'
Can someone please help me with this?
Solution 1:[1]
You could also use iterrows() for this like so:
df = pd.DataFrame({'BTC obtained':[0.00567,0.00054,0.00230]})
print(df)
n=0
for index, row in df.iterrows():
n+=row["BTC obtained"]
print(n)
Output
0.00567
0.006209999999999999
0.00851
Solution 2:[2]
If you see the documentation of iteritems, you will see that the command yields two things:
- label: object
- content: Series
That means that v will be a tuple (label, content). If you want to access the series you will have to access v[1].
Alternatively, you can do:
for label, v in x.iteritems():
Based on your comment, it seems like you want the cumulative summation of the elements. You can do this without a for loop, by using pandas cumsum:
n = x.cumsum()
If you want to use a for loop you can do the following:
n=0
for label, v in x.iteritems():
n+=v['BTC obtained']
print(n)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kcode |
| Solution 2 |
