【问题标题】:how to find rows with both positive and negative values in pandas dataframe如何在熊猫数据框中找到具有正值和负值的行
【发布时间】:2019-07-06 08:34:13
【问题描述】:

我有一个这样的数据框:

     e_col   in_col     word_col      w_col
     31      9        algorithm    -0.053538
     31      9              ubc    -0.053578
     31      9              kth    -0.053595
     31      8              ubc    -0.053633
     30      8        algorithm     0.043637
     30      7             dale     0.053648
     28      6             dale     0.053671

我想在w_col 中找到相同word_col 得到正值和负值的行。

所以,例如这里的输出将是:

 31      9        algorithm    -0.053538
 30      8        algorithm     0.043637

【问题讨论】:

  • 也许你可以groupby(['word_col']) 然后分别检查每个组。如果组有 group['w_col'] >= 0group['w_col'] < 0 那么你有你的行。
  • 感谢关注@furas,我尝试了各种版本的print(df.groupby('word').apply([(df['w_col']<0) & (df['w_col']>0)])),但要么引发错误,要么不是我预期的输出。
  • 如果您尝试过此操作,请输入此信息并添加完整的错误消息。如果您创建我们可以复制和运行的最小工作代码,那么也许有人会创建解决方案。
  • 我试图用我做过的最复杂的事情来更新,并得到了答案。谢谢。

标签: python pandas dataframe


【解决方案1】:

编辑2:您也可以使用transform 来避免set_index/reset_index,如下所示:

m = df.w_col.lt(0).groupby(df.word_col).transform('nunique').eq(2)
df.loc[m]

Out[2768]:
   e_col  in_col   word_col     w_col
0     31       9  algorithm -0.053538
4     30       8  algorithm  0.043637

编辑 1:创建m 的更短的方法是使用nunique(),如下所示:

m =  df.w_col.lt(0).groupby(df.word_col).nunique().eq(2)

原创
执行以下操作:在w_col 上创建小于0groupby 的布尔掩码word_col。接下来,在每个组上调用unique 并找到具有len = 2 的任何组。将其用作在df.set_indexreset_index 上索引的掩码。

m = df.w_col.lt(0).groupby(df.word_col).unique().str.len().eq(2)
df.set_index('word_col').loc[m].reset_index()

Out[2738]:
    word_col  e_col  in_col     w_col
0  algorithm     31       9 -0.053538
1  algorithm     30       8  0.043637

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2021-06-16
    • 2015-11-01
    • 2014-02-13
    • 2020-08-14
    • 2021-03-10
    • 2017-08-11
    相关资源
    最近更新 更多