在Python中清除dataframe中的非布尔值

2024-09-29 22:24:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,其中的列都是布尔值(1或0),但是有些列的值无效,比如:111、10、11。我需要通过删除包含无效值的数据行来清除数据。但是在清除非布尔值之前,第一列是Age,我需要通过将它们放在18-150的范围内来清理行,因为有700或600这样的值。在

cleandata4bestdeal2=cleandata4bestdeal.dropna(axis=0,how=any,inplace = False)

我已经删除了值为NaN的行,但我正在使用上面的方法删除所有非布尔值。
CleanDataFrame


Tags: 数据方法falsedataframeageanynanhow
1条回答
网友
1楼 · 发布于 2024-09-29 22:24:48
# create some sample data, since none was provided
>>> df = pd.DataFrame({'Age': [15, 700, 600, 150, 125, 32, 45, 43, 56, 1002], 'Boolean': ['001', '100', '0', '1', '1', '010', '110', '1', '0', '0']})
>>> print(df)
    Age Boolean
0    15     001
1   700     100
2   600       0
3   150       1
4   125       1
5    32     010
6    45     110
7    43       1
8    56       0
9  1002       0

# keep only those rows for which the 'Age' column is in the inclusive range [18, 150]
>>> new_df = df[df['Age'].isin(range(18, 151))]
>>> print(new_df)
   Age Boolean
3  150       1
4  125       1
5   32     010
6   45     110
7   43       1
8   56       0

# finally, keep only those boolean values that are of length 1 
# (i.e. exclude rows with 'Boolean' values like '110' or '010')
>>> new_df = new_df[new_df['Boolean'].map(len) == 1]
>>> print(new_df)
   Age Boolean
3  150       1
4  125       1
7   43       1
8   56       0

相关问题 更多 >

    热门问题