我無法弄清楚為什么我添加到的資料框“newTimeDF”在 for 回圈結束時為空:
timeZonesDF = pd.DataFrame{"timeZoneDate": [2018-03-11, 2018-11-04]}
newTimeDF = pd.DataFrame(columns = ["startDate", "endDate"])
for yearRow, yearData in timeZonesDF.groupby(pd.Grouper(freq="A")):
DST_start = pd.to_datetime(yearData.iloc[0]["timeZoneDate"])
DST_end = pd.to_datetime(yearData.iloc[-1]["timeZoneDate"])
newTimeDF["startDate"] = DST_start
newTimeDF["endDate"] = DST_end
continue
有人可以指出我缺少什么,groupby for-loops 有什么不同嗎?
uj5u.com熱心網友回復:
你在這里的代碼:
newTimeDF["startDate"] = DST_start
newTimeDF["endDate"] = DST_end
將所有行的 startDate 列設定為等于 DST_start,將所有行的 endDate 列設定為等于 DST_end。因為在運行此代碼時,您的資料框沒有行,您的最終產品沒有任何更改。
您可以做的是根據您的兩個值創建一個字典,如下所示:
tempdic = {"startDate" : DST_start, "endDate" : DST_end}
然后將該字典附加到您的資料框以添加一行。
newTimeDF.append(tempdic, ignore_index=True)
讓你的代碼看起來像這樣
for yearRow, yearData in timeZonesDF.groupby(pd.Grouper(freq="A")):
DST_start = pd.to_datetime(yearData.iloc[0]["timeZoneDate"])
DST_end = pd.to_datetime(yearData.iloc[-1]["timeZoneDate"])
tempdic = {"startDate" : DST_start, "endDate" : DST_end}
newTimeDF = newTimeDF.append(tempdic, ignore_index=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/313514.html
標籤:Python 熊猫 for循环 pandas-groupby
上一篇:如何組合陣列中的元素?
