Python 2.7 Python-数据帧中的增量函数
我想从数据帧创建一个增量函数。 Me数据帧如下所示:Python 2.7 Python-数据帧中的增量函数,python-2.7,increment,Python 2.7,Increment,我想从数据帧创建一个增量函数。 Me数据帧如下所示: ___________ ___________ | Action_ID | Unique_ID | | 4 | | | 3 | | | 2 | | | 1 | | | 4 | | ___________ ___________ 要在操作\u ID egals
___________ ___________
| Action_ID | Unique_ID |
| 4 | |
| 3 | |
| 2 | |
| 1 | |
| 4 | |
___________ ___________
要在操作\u ID egals 4时设置唯一\u ID egals i+1。因此:
___________ ___________
| Action_Id | Unique_Id |
| 4 | 1 |
| 3 | |
| 2 | |
| 1 | |
| 4 | 2 |
___________ ___________
我尝试了以下代码:
def order_code(grp):
i=0
if(grp.loc[grp.first_valid_index(),'Action_Id']==4):
i = i+1
grp['Unique_Id']=i
return(grp)
c=(c.groupby('Action_Id')).apply(order_code)
但它向我展示了:
___________ ___________
| Action_Id | Unique_Id |
| 4 | 1 |
| 3 | |
| 2 | |
| 1 | |
| 4 | 1 |
___________ ___________
有人能帮我吗?您的问题是
i
在您正在使用的功能范围内。例如,如果您要执行以下操作:
inc = 0
def order_code(grp):
global inc
if(grp.loc[grp.first_valid_index(),'Action_Id']==4):
inc += 1
grp['Unique_Id']=inc
return(grp)
c=(c.groupby('Action_Id')).apply(order_code)
它会起作用。您的问题是
i
在您正在使用的函数的范围内。例如,如果您要执行以下操作:
inc = 0
def order_code(grp):
global inc
if(grp.loc[grp.first_valid_index(),'Action_Id']==4):
inc += 1
grp['Unique_Id']=inc
return(grp)
c=(c.groupby('Action_Id')).apply(order_code)
这会有用的。谢谢Eli的快速回答。不过,我已经尝试了你的代码,它显示与我的函数相同(1,而不是增量)。感谢Eli的快速回答。但是,我已经尝试了您的代码,它显示与我的函数相同(1,而不是增量)。