所以我想用加入日期后一個月的日期填充支付日期的 NaN 值。
| 加入日期 | 發薪日1 |
|---|---|
| okt'10 | 鈉 |
| Des'10 | 鈉 |
我的期望輸出是:
| 加入日期 | 發薪日1 |
|---|---|
| okt'10 | 10 年 11 月 |
| Des'10 | 11 年 1 月 |
我試試這段代碼:
months = ["Jan", "Feb", "Mar", "Apr","Mei","Jun","Jul","Agt","Sep","Okt","Nov","Des"]
dateIn="Okt'10"
def fill_date():
dateIn=dateIn.split("'")
month, year= dateIn[0], int(dateIn[1])
if month == months[len(months)-1]:
year =1
month=months[0]
else:
for m in months:
if m == month:
month=months[months.index(month) 1]
dateOut=f"{month} {year}"
df['Payday1'] = df['Payday1'].apply(fill_date)
此代碼在此代碼month=months[months.index(month) 1]中是錯誤的,它說list index out of range。那么如何修復此代碼?
uj5u.com熱心網友回復:
嘗試:
def fill_date(dt):
mapper = {m: i 1 for i, m in enumerate(months)}
month, year = dt.split("'")
if mapper[month]==12:
return f"Jan'{int(year) 1}"
else:
return f"{months[mapper[month]]}'{year}"
df["Payday1"] = df["Join date"].apply(fill_date)
輸入 df:
df = pd.DataFrame({"Join date": ["Okt'10", "Des'10"]})
uj5u.com熱心網友回復:
如果要限制和之間的索引0,len(months)可以使用模運算子%。
month=months[(months.index(month) 1) % len(months)]
所以你會得到以下資訊:
def fill_date(dateIn):
dateIn = dateIn.split("'")
month, year = dateIn[0], int(dateIn[1])
year = 1 if month == months[-1] else 0
month = months[(months.index(month) 1) % len(months)]
dateOut = f"{month}'{year}"
return dateOut
uj5u.com熱心網友回復:
我看到兩種方法:
第一:Jan在串列末尾添加第二個,months這可能有效。
第二:找到第一個匹配元素時使用breakinside -loop 退出它。for
所有問題都是因為在if m == month你為和下一個回圈分配新值的內部month,同一行if m == month與不同的值比較 inmonth并且它可能與Des和 tor 比較以獲得 elemenet 之后Des。但是如果你使用break它,它將在找到第一個匹配值后退出(并且它不會檢查if m == month新值)。
具有其他更改的完整作業代碼 - 即。你return dateOut在你的代碼中迷失了。
months = ["Jan", "Feb", "Mar", "Apr","Mei","Jun","Jul","Agt","Sep","Okt","Nov","Des"]
dateIn = "Okt'10"
import pandas as pd
df = pd.DataFrame({
'Join date': ["Okt'10", "Des'10"],
'Payday1': ["NaN", "NaN"],
})
def fill_date(dateIn):
print(dateIn)
dateIn = dateIn.split("'")
month, year = dateIn[0], int(dateIn[1])
if month == months[-1]:
year = 1
month = months[0]
else:
for m in months:
if m == month:
month = months[months.index(month) 1]
break # <--- HERE
dateOut = f"{month}'{year}"
return dateOut
df['Payday1'] = df['Join date'].apply(fill_date)
print(df)
結果:
Join date Payday1
0 Okt'10 Nov'10
1 Des'10 Jan'11
可能問題也可以解決以從串列for m in months[:-1]:中跳過。Des
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472584.html
