根据现有列分配真/假条件

3 投票
2 回答
691 浏览
提问于 2025-06-18 04:12

我需要在某个条件满足时,给出一个真/假(True/False)的值。

具体来说,我有一个数据表(dataframe)

col1      col2    col3   col4   col5    col6   col7    col8   col9
Number1   True   False   True   False   True   False   True   False
Number2   False  False   False  False   False  False   False  False
Number3   True   False   False  False   False  False   False  False
Number4   False  False   False  False   False  True    False  False

我想根据这些真/假的值创建一个新列。如果至少有一个值是True,那么在新列中就标记为True;如果所有值都是False,那就在新列中标记为False。

根据上面的例子,我应该得到:

col1      col2    col3   col4   col5    col6   col7    col8   col9     col10
Number1   True   False   True   False   True   False   True   False    True
Number2   False  False   False  False   False  False   False  False    False
Number3   True   False   False  False   False  False   False  False    True
Number4   False  False   False  False   False  True    False  False    True

我试过用

if (df['COL1'], df['COL2'], df['COL3'], df['COL4'], df['COL5'], df['COL6'], df['COL7'], df['COL8'], df['COL9']).any():
                df[index,'COL10'] = True
            else:
                df[index,'COL10'] = False

但是这样会把所有的值都标记为True。

你能帮我得到正确的结果吗?非常感谢!

相关问题:

  • 暂无相关问题
暂无标签

2 个回答

0

你在这里犯了两个错误。一个是没有遍历每一行,另一个是在表达式中用了col1。
这是我尝试过的,和你做的方式类似。

df['col10'] = False
for index, row in df.iterrows():
    if row['col2'] or row['col3'] or row['col4'] or row['col5'] or row['col6'] or row['col7'] or row['col8'] or row['col9']:
        df.iloc[index,9] = True
    else:
        df.iloc[index,9] = False

这个问题的单行解决方案是:

df['col10'] = df.loc[:,'col2':].any(1)
4

只需要使用 any 就可以了。

df.loc[:,'col2':].any(1)
0     True
1    False
2     True
3     True
dtype: bool

#df['col10']=df.loc[:,'col2':].any(1)

撰写回答