根据列上函数的结果对Pandas Dataframe进行切片

乔治娜·桃

我想使用基于DateTime列月份的条件(逐元素)对数据框进行切片:

Met_Monthly_DF = Metsite_DF.iloc[Metsite_DF['DateTime'].month == Month]

我得到错误:

builtins.AttributeError: 'Series' object has no attribute 'month'

如果我确实说,它可以逐个元素地工作:

Months = [DT.month for DT in Metsite_DF['DateTime'].tolist()]

如何应用此条件?

耶斯列尔

有两个问题:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章