有2个问题:
Met_Monthly_DF = Metsite_DF.loc[Metsite_DF['DateTime'].dt.month == Month]
示例:
Metsite_DF = pd.DataFrame({'col':list('abcd'),
'DateTime':pd.date_range('2017-01-01', periods=4, freq='16D')})
print (Metsite_DF)
DateTime col
0 2017-01-01 a
1 2017-01-17 b
2 2017-02-02 c
3 2017-02-18 d
Month = 2
Met_Monthly_DF = Metsite_DF.loc[Metsite_DF['DateTime'].dt.month == Month]
print (Met_Monthly_DF)
DateTime col
2 2017-02-02 c
3 2017-02-18 d
或者删除iloc,但显然需要copy以避免SettingWithCopyWarning:
Met_Monthly_DF = Metsite_DF[Metsite_DF['DateTime'].dt.month == Month].copy()
如果您稍后修改 Met_Monthly_DF 中的值,您会发现修改不会传播回原始数据 (Metsite_DF),并且 Pandas 会发出警告。
Month = 2
Met_Monthly_DF = Metsite_DF[Metsite_DF['DateTime'].dt.month == Month]
#filter dataframe is modified - e.g. added new column for years
Met_Monthly_DF['new'] = Met_Monthly_DF['DateTime'].dt.year
print (Met_Monthly_DF)
DateTime col new
2 2017-02-02 c 2017
3 2017-02-18 d 2017
SettingWithCopyWarning:
试图在 DataFrame 中的切片副本上设置值。
尝试改用 .loc[row_indexer,col_indexer] = value
请参阅文档中的注意事项:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
Month = 2
Met_Monthly_DF = Metsite_DF[Metsite_DF['DateTime'].dt.month == Month].copy()
Met_Monthly_DF['new'] = Met_Monthly_DF['DateTime'].dt.year
print (Met_Monthly_DF)
DateTime col new
2 2017-02-02 c 2017
3 2017-02-18 d 2017