我搞不懂为什么数据框" newtimef ";我在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循环是不同的?
您在这里的代码:
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)