迭代dataframe列并在python中创建新列
我有一个这样的数据帧迭代dataframe列并在python中创建新列,python,pandas,Python,Pandas,我有一个这样的数据帧dataframe 我想创建一个新列(seq)并执行以下操作 df['seq']=每组的第一项(按id)为0 df['seq']=保持增量,直到在日期列中按组(按id)看到日期 如果存在日期,则再次按照相同的增量过程将列seq重置为0 这是我的预期答案预期输出: 谢谢我想到的最简单的解决方案是创建一个数组,并在循环数据帧时用计数器的值填充它。之后将添加新列 例如: seq = np.zeros(len(df)) date = '' id = 0 counter = 0
dataframe
我想创建一个新列(seq)并执行以下操作
=每组的第一项(按id)为0df['seq']
=保持增量,直到在日期列中按组(按id)看到日期df['seq']
- 如果存在日期,则再次按照相同的增量过程将列seq重置为0
谢谢我想到的最简单的解决方案是创建一个数组,并在循环数据帧时用
计数器的值填充它。之后将添加新列
例如:
seq = np.zeros(len(df))
date = ''
id = 0
counter = 0
for i in range(len(df)):
test_date = df['Dates'].iloc[i]
test_id = df['id'].iloc[i]
if (test_date and test_date != date) or (test_id != id):
# new date or id detected
date = test_date
id = test_id
counter = 0
else:
counter += 1
seq[i] = counter
df['seq'] = seq
这可能是一种更有效的方法,但根据我的经验,使用numpy数组在dataframe中添加数据时,性能还可以