I’ve seen this question for R, but not for python.
Basically, I have a large DataFrame where I apply a function row-wise. It takes a very long time to run and I hoped to put a print statement to show where I am. I put together an example of what I would like to do.
I know an alternative, but I wondered if possible with apply.
So this would work fine
JavaScript
x
12
12
1
import pandas as pd
2
3
df = pd.DataFrame({0: [1,2,3], 1:[2,3,4], 2: [0,0,0]})
4
5
i = 0
6
for rows in df:
7
print ("Current row: {}".format(i))
8
df[2][i] = df[0][i] * df[1][i]
9
i += 1
10
11
print (df)
12
Output
JavaScript
1
9
1
Current row: 0
2
Current row: 1
3
Current row: 2
4
5
0 1 2
6
0 1 2 2
7
1 2 3 6
8
2 3 4 12
9
But I hoped to do something with apply such as:
JavaScript
1
6
1
def func(df):
2
#something here to print
3
return df[0] * df[1]
4
5
df[2] = df.apply(func,axis=1)
6
Many thanks.
Advertisement
Answer
I guess you can write your function like this:
JavaScript
1
4
1
def func(df):
2
print(f'Current row: {df.name}')
3
return df[0] * df[1]
4
The usage is following:
JavaScript
1
5
1
>>> df[2] = df.apply(func, axis=1)
2
Current row: 0
3
Current row: 1
4
Current row: 2
5