![](/img/trans.png)
[英]Iterating over rows in a pandas dataframe with a condition to create a new column
[英]Iterating over dataframe column and creating new column in python pandas
對我來說最簡單的解決方案是創建一個數組並在循環遍歷 dataframe 時用counter
的值填充它。 您將在之后添加新列。
例如:
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 中添加數據時性能還可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.