【问题标题】:Replacing integers of all columns of a pandas dataframe with True/False用 True/False 替换 pandas 数据框所有列的整数
【发布时间】:2020-09-25 23:39:22
【问题描述】:

我有一个带有整数的 pandas 数据框。

对于我的数据框中的所有列,我想用True 替换1 和用False 替换2,所以只用布尔值制作一个数据框。

我想我会尝试使用df[Col] = df[Col].astype(bool) 之类的东西来遍历所有列,但是当我在Col1 上尝试它时,它只是用True 替换了Col1 中的每个值。 TrueTrueFalseTrue

感谢您的帮助!

import pandas as pd

data = {'Col1': [1,1,2,1],
        'Col2': [2,2,1,1],
        'Col3': [1,1,1,2],
        'Col4': [2,1,2,2]
        }

df = pd.DataFrame(data, columns = ['Col1', 'Col2', 'Col3', 'Col4'])

【问题讨论】:

    标签: python pandas boolean


    【解决方案1】:

    只需使用:

    df == 1
    

    输出:

        Col1   Col2   Col3   Col4
    0   True  False   True  False
    1   True  False   True   True
    2  False   True   True  False
    3   True   True  False  False
    

    【讨论】:

    • 您的回答总是让我感到惊讶。 +1
    • @Ch3steR 谢谢。感谢您的评论。
    【解决方案2】:
    import pandas as pd
    
    data = {'Col1': [1,1,2,1],
            'Col2': [2,2,1,1],
            'Col3': [1,1,1,2],
            'Col4': [2,1,2,2]
            }
    
    df = pd.DataFrame(data, columns = ['Col1', 'Col2', 'Col3', 'Col4'])
    df = df.replace(1,True)
    df = df.replace(2,False)
    df
    

    输出:

        Col1    Col2    Col3    Col4
    0   True    False   True    False
    1   True    False   True    True
    2   False   True    True    False
    3   True    True    False   False
    

    【讨论】:

      【解决方案3】:

      您可以使用df.replace

      df.replace([1,2],[True,False])
      

      【讨论】:

        【解决方案4】:

        给你:

        >>> df == 1                      
            Col1   Col2   Col3   Col4
        0   True  False   True  False
        1   True  False   True   True
        2  False   True   True  False
        3   True   True  False  False
        
        

        【讨论】:

          【解决方案5】:

          问题在于,在整数的上下文中,.astype(bool) 将所有非零整数更改为 True,将所有零更改为 False。我会使用map 如下:

          df[Col] = df[Col].map({1:True, 2:False})

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-12-05
            • 2019-01-14
            • 2018-09-29
            • 2018-07-11
            • 2018-03-18
            • 2022-06-24
            • 1970-01-01
            相关资源
            最近更新 更多