【问题标题】:Slice a Pandas Dataframe based on the results of a function on a column根据列上函数的结果对 Pandas 数据框进行切片
【发布时间】:2018-06-15 06:48:43
【问题描述】:

我想使用基于 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()]

如何应用此条件?

【问题讨论】:

    标签: python pandas dataframe slice series


    【解决方案1】:

    有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
    

    【讨论】:

    • 感谢耶斯瑞尔!只要 Month 是整数,您的解决方案就很有效!
    猜你喜欢
    • 2017-05-21
    • 2020-12-26
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    相关资源
    最近更新 更多