Pandas:根据布尔条件更改多个列中的值

2024-05-22 01:34:35 发布

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

这应该是一件很简单的事情,但不知怎么的,我还不能把我的头都放在大熊猫身上选择和掩蔽东西的所有不同方法上。在

所以对于一个大数据帧(从csv文件中读取),我想根据一些布尔条件(在相同的选定列上测试)更改列列表的值。在

我已经尝试过类似的方法,但由于尺寸不匹配而无效:

df.loc[df[my_cols]>0, my_cols] = 1

这也不起作用(因为我试图更改错误列中的值):

^{pr2}$

但这不起作用,因为我只更改了数据帧的一个副本:

df[my_cols][df[my_cols]>0] = 1

以下是df.info的输出:

Int64Index: 186171 entries, 0 to 186170
Columns: 737 entries, id to 733:zorg
dtypes: float64(734), int64(1), object(2)
memory usage: 1.0+ GB

一些更先进的熊猫用户能帮忙吗?谢谢您。在


Tags: 文件csvto数据方法df列表my
3条回答

我很确定还有一种更优雅的方式,但这应该是可行的:

df = pd.DataFrame(np.random.randint(5, size=(3,4)), columns = ['a','b','c','d'])
mycols =['a','b']
cols_tochange = df.columns[df[mycols].all()>1]
df.loc[:,cols_tochange]  = 1

注意使用all(),以获得整个列的条件

尝试pandas.DataFrame.where

Return an object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other.

在您的情况下,这将变成:

df[my_cols] = df[my_cols].where(~(df[my_cols]>0),other=1)

这就是我如何最终得到了预期的结果,但我觉得必须有一个更像熊猫的解决方案来完成这项任务。在

for col in my_cols:
    df.loc[df[col]>0, col] = 1 

相关问题 更多 >