【问题标题】:Python: Maintain multiple columns with np.wherePython:使用 np.where 维护多个列
【发布时间】:2018-03-23 10:13:08
【问题描述】:

是否可以使用 np.where 一次维护多个列? 通常,一列由 np.where 维护,所以我的编码如下所示:

df['col1] = np.where(df[df.condition == 'yes'],'sth', '')
df['col2'] = np.where(df[df.condition == 'yes'], 50.00, 0.0)

但是由于我两次测试相同的条件,我想知道我是否可以通过 2 列并在一次运行中填充它们。

我试过这个:

df['col1','col2'] = np.where(df[df.condition == 'yes'],['sth',50.00], ['',0.0])

但它不起作用。有没有办法实现这一点?

谢谢:)

【问题讨论】:

  • “一次维护多个列”是什么意思?您能否展示您拥有的数据样本以及您想要达到的结果?
  • @jezrael,我很难理解这个问题。如果您理解它,介意编辑问题吗?我可以看到这让很多用户感到困惑,而不仅仅是我!

标签: python pandas dataframe


【解决方案1】:

我认为需要将布尔掩码重塑为(N x 1)

m = df.condition == 'yes'
df[['col1','col2']] = pd.DataFrame(np.where(m[:, None], ['sth',50.00], ['',0.0]))

解决方案的唯一缺点是如果 lists 中的不同类型的值 - 带有 strings 的数字 - 然后 numpy.where 两个输出列都转换为 strings。

示例

df = pd.DataFrame({'A':list('abcdef'),
                     'condition':['yes'] * 3 + ['no'] * 3})

print (df)
   A condition
0  a       yes
1  b       yes
2  c       yes
3  d        no
4  e        no
5  f        no

m = df.condition == 'yes'
df[['col1','col2']] = pd.DataFrame(np.where(m[:, None], ['sth',50.00], ['',0.0]))
print (df)
   A condition col1  col2
0  a       yes  sth  50.0
1  b       yes  sth  50.0
2  c       yes  sth  50.0
3  d        no        0.0
4  e        no        0.0
5  f        no        0.0

print (df.applymap(type))
               A      condition           col1           col2
0  <class 'str'>  <class 'str'>  <class 'str'>  <class 'str'>
1  <class 'str'>  <class 'str'>  <class 'str'>  <class 'str'>
2  <class 'str'>  <class 'str'>  <class 'str'>  <class 'str'>
3  <class 'str'>  <class 'str'>  <class 'str'>  <class 'str'>
4  <class 'str'>  <class 'str'>  <class 'str'>  <class 'str'>
5  <class 'str'>  <class 'str'>  <class 'str'>  <class 'str'>

编辑:我用NaNs 值测试它:

df = pd.DataFrame({'A':list('abcdefghi'),
                     'condition':['yes'] * 3 + ['no'] * 3 + [np.nan] * 3})

m = df.condition == 'yes'
df[['col1','col2']] = pd.DataFrame(np.where(m[:, None], ['sth',50.00], ['',0.0]))
print (df)
   A condition col1  col2
0  a       yes  sth  50.0
1  b       yes  sth  50.0
2  c       yes  sth  50.0
3  d        no        0.0
4  e        no        0.0
5  f        no        0.0
6  g       NaN        0.0
7  h       NaN        0.0
8  i       NaN        0.0

【讨论】:

  • 谢谢,这几乎可行。任何想法,为什么它不适用于最后 6 行? col1 和 col2 在最后几行中都包含 nan,所有其他行都有有效内容。
  • @MaMo - 嗯,似乎有问题需要另一个条件来排除NaNs
  • @MaMo - 我添加了示例以使用NaNs 进行回答,并且效果很好。你能测试一下吗?还是我不明白你需要什么?
  • 我在 col1 和 col2 中得到 NaNs 最后几行,而不是在条件列中。我不知道原因,因为这些行或条件列没有什么特别之处。
  • @MaMo - 没有难以知道的数据,数据是否可信?
猜你喜欢
  • 1970-01-01
  • 2021-07-16
  • 2016-08-04
  • 2017-02-02
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多