【问题标题】:Pandas DataFrame: replace all values in a column, based on conditionPandas DataFrame:根据条件替换列中的所有值
【发布时间】:2015-10-09 07:26:33
【问题描述】:

我有一个简单的 DataFrame,如下所示:

我想从“第一季”列中选择所有值,并将超过 1990 年的值替换为 1。在此示例中,只有巴尔的摩乌鸦队会将 1996 年替换为 1(保持其余数据不变)。

我用过以下:

df.loc[(df['First Season'] > 1990)] = 1

但是,它将该行中的所有值替换为 1,而不仅仅是“第一季”列中的值。

如何仅替换该列中的值?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    另一种选择是使用列表推导:

    df['First Season'] = [1 if year > 1990 else year for year in df['First Season']]
    

    【讨论】:

    • 当您需要直接处理值而不是使用常量值时,这是最佳选择。
    【解决方案2】:
    df.loc[df['First season'] > 1990, 'First Season'] = 1
    

    解释:

    df.loc 接受两个参数,“行索引”和“列索引”。我们正在检查“第一季”列下每行值的值是否大于 1990,然后我们将其替换为 1。

    【讨论】:

      【解决方案3】:

      我们可以使用以下语法更新 df 中的 First Season 列:

      df['First Season'] = expression_for_new_values
      

      要映射第一季中的值,我们可以使用 pandas 的 .map() 方法,语法如下:

      data_frame(['column']).map({'initial_value_1':'updated_value_1','initial_value_2':'updated_value_2'})
      

      【讨论】:

        【解决方案4】:

        对于单一条件,即。 ( 'employrate'] > 70 )

               country        employrate alcconsumption
        0  Afghanistan  55.7000007629394            .03
        1      Albania  51.4000015258789           7.29
        2      Algeria              50.5            .69
        3      Andorra                            10.17
        4       Angola  75.6999969482422           5.57
        

        使用这个:

        df.loc[df['employrate'] > 70, 'employrate'] = 7
        

               country  employrate alcconsumption
        0  Afghanistan   55.700001            .03
        1      Albania   51.400002           7.29
        2      Algeria   50.500000            .69
        3      Andorra         nan          10.17
        4       Angola    7.000000           5.57
        

        因此这里的语法是:

        df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]
        

        对于多个条件,即。 (df['employrate'] &lt;=55) &amp; (df['employrate'] &gt; 50)

        使用这个:

        df['employrate'] = np.where(
           (df['employrate'] <=55) & (df['employrate'] > 50) , 11, df['employrate']
           )
        

        out[108]:
               country  employrate alcconsumption
        0  Afghanistan   55.700001            .03
        1      Albania   11.000000           7.29
        2      Algeria   11.000000            .69
        3      Andorra         nan          10.17
        4       Angola   75.699997           5.57
        

        因此这里的语法是:

         df['<column_name>'] = np.where((<filter 1> ) & (<filter 2>) , <new value>, df['column_name'])
        

        【讨论】:

          【解决方案5】:
          df['First Season'].loc[(df['First Season'] > 1990)] = 1
          

          奇怪的是没有人有这个答案,你的代码中唯一缺少的部分是 df 之后的 ['First Season'] ,只需删除里面的大括号。

          【讨论】:

          【解决方案6】:

          聚会有点晚了,但仍然 - 我更喜欢使用 numpy where:

          import numpy as np
          df['First Season'] = np.where(df['First Season'] > 1990, 1, df['First Season'])
          

          【讨论】:

          • 我正在寻找有条件地覆盖列值的解决方案,但基于其他列的值,如下所示:df['col1'] = np.where(df['id'] == '318431682259014', 'NEW', df['col1']) 这就是它的解决方案。
          • 我正在尝试针对这样的多种情况执行此操作,但我不断收到ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()。我想做的基本上是df['A'] = np.where(df['B'] in some_values, df['A']*2, df['A]。有人对此有想法吗?
          • 现在pandas内置了where方法,和pandas.pydata.org/pandas-docs/stable/reference/api/…中的np.where比较
          • 我在玩这个 df,发现如果你将代码更改为 ...nfl_df['First Season'] = np.where(nfl_df['First Season'] > 1990, 1 , nfl_df['Total Games']) 然后它将第一季中的所有值替换为 Total Games 中的值,而不仅仅是 1990 年以上的值。为什么要这样做?这似乎不太合乎逻辑。
          【解决方案7】:

          您需要选择该列:

          In [41]:
          df.loc[df['First Season'] > 1990, 'First Season'] = 1
          df
          
          Out[41]:
                           Team  First Season  Total Games
          0      Dallas Cowboys          1960          894
          1       Chicago Bears          1920         1357
          2   Green Bay Packers          1921         1339
          3      Miami Dolphins          1966          792
          4    Baltimore Ravens             1          326
          5  San Franciso 49ers          1950         1003
          

          所以这里的语法是:

          df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]
          

          您可以查看docs 以及显示语义的10 minutes to pandas

          编辑

          如果你想生成一个布尔指标,那么你可以只使用布尔条件来生成一个布尔系列并将 dtype 转换为 int 这会将 TrueFalse 转换为 10分别:

          In [43]:
          df['First Season'] = (df['First Season'] > 1990).astype(int)
          df
          
          Out[43]:
                           Team  First Season  Total Games
          0      Dallas Cowboys             0          894
          1       Chicago Bears             0         1357
          2   Green Bay Packers             0         1339
          3      Miami Dolphins             0          792
          4    Baltimore Ravens             1          326
          5  San Franciso 49ers             0         1003
          

          【讨论】:

            猜你喜欢
            • 2018-09-26
            • 2022-07-05
            • 2020-06-22
            • 2022-12-22
            • 2021-09-25
            • 1970-01-01
            • 2019-02-12
            • 2018-04-24
            • 2021-09-05
            相关资源
            最近更新 更多