我见过R的这个问题,但没有见过python的问题。
基本上,我有一个大的DataFrame,我在其中按行应用一个函数。运行需要很长时间,我希望能打印一份声明来显示我的位置。我举了一个我想做什么的例子。
我知道另一种选择,但我想知道是否可以申请。
所以这会很好
import pandas as pd
df = pd.DataFrame({0: [1,2,3], 1:[2,3,4], 2: [0,0,0]})
i = 0
for rows in df:
print ("Current row: {}".format(i))
df[2][i] = df[0][i] * df[1][i]
i += 1
print (df)
输出
Current row: 0
Current row: 1
Current row: 2
0 1 2
0 1 2 2
1 2 3 6
2 3 4 12
但我希望对应用程序做一些事情,比如:
def func(df):
#something here to print
return df[0] * df[1]
df[2] = df.apply(func,axis=1)
非常感谢。
我想你可以这样写函数:
def func(df):
print(f'Current row: {df.name}')
return df[0] * df[1]
用法如下:
>>> df[2] = df.apply(func, axis=1)
Current row: 0
Current row: 1
Current row: 2
您可以使用series.name
:
>>> def mul(row):
print('Current row:', row.name)
return row[0] * row[1]
>>> df[2] = df.apply(mul, axis=1);print(df)
Current row: 0
Current row: 1
Current row: 2
0 1 2
0 1 2 2
1 2 3 6
2 3 4 12