[英]Create a counter for each row processed in apply function
I was wondering if it is possible to create a counter for each row as you apply a function to a Pandas dataframe like this:我想知道当您将 function 应用于 Pandas dataframe 时,是否可以为每一行创建一个计数器,如下所示:
data['column'] = data.apply(lambda x: function(x['url']), axis=1)
The output should be something similar to this: output 应该与此类似:
1
2
3
4
5
...
Thanks谢谢
If your data frame has got row indices named by numbers, like this one:如果您的数据框有以数字命名的行索引,如下所示:
>> df = pd.DataFrame(
[
{'var_1': 23, 'var_2': 25},
{'var_1': 24, 'var_2': 26},
{'var_1': 25, 'var_2': 27},
{'var_1': 26, 'var_2': 28},
]
)
>> print(df)
var_1 var_2
0 23 25
1 24 26
2 25 27
3 26 28
you can use this piece of code:你可以使用这段代码:
>> df['cnt'] = df.apply(lambda row: row.name + 1, axis=1)
>> print(df)
var_1 var_2 cnt
0 23 25 1
1 24 26 2
2 25 27 3
3 26 28 4
However, the other option, how to reach the result (without .apply
method), can be this one:但是,另一个选项,如何达到结果(没有.apply
方法)可以是这个:
>> df['cnt_1'] = range(1, len(df) + 1)
>> print(df)
var_1 var_2 cnt cnt_1
0 23 25 1 1
1 24 26 2 2
2 25 27 3 3
3 26 28 4 4
One possible solution is add x.name
parameter to your function and use print
for apply-indicator
:一种可能的解决方案是将x.name
参数添加到您的 function 并将print
用于apply-indicator
:
data = pd.DataFrame({'url':['a','b','c']})
def function(x, y):
#return progress indicator by index values
print (y)
#sample function
return x + '_'
0
1
2
data['column'] = data.apply(lambda x: function(x['url'], x.name), axis=1)
print (data)
url column
0 a a_
1 b b_
2 c c_
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.