【问题标题】:Undesired results when using .sample() with .where() in Python在 Python 中将 .sample() 与 .where() 一起使用时出现不希望的结果
【发布时间】:2020-12-02 16:47:58
【问题描述】:

我正在尝试从满足条件的数据框中选择 2 个随机值。 请看下面的例子df:

data = {'col1':  ['abc', 'def','ghi','jkl','mno','pqr','stu','vwx','yz'],
        'col2': ['4', '1','4','4','0','1','4','2','4'],
        'col3': ['Sweden', 'Malaysia','Sweden','Venezuela','France','Sweden','Australia','Belgium','Sweden']
        }

df = pd.DataFrame (data, columns = ['col1','col2','col3'])

我想从 'col1' 中选择 2 个随机值,其中 'col2' 等于 4。然后我使用的代码是:

print(df['col1'].sample(n=2).where(df['col2']==4))

期望的输出是:

0  abc
6  stu

....或

8  yz
2 ghi 

但是代码目前给出的输出如下:

7    NaN
3    NaN

这是不可取的,因为a)我希望看到一个字符串值作为文本,b)虽然对应于第 3 行的值符合标准,但对应于第 7 行的值不符合标准,因此标准不是在所有情况下都得到满足。

问题:

  1. 如何修改我的代码,使其返回文本值并且仅在满足条件的情况下返回
  2. 如何添加第二个条件,例如.where(df['col2']==4) & (df['col3']=='Sweden')

感谢您在此提供任何指导。

【问题讨论】:

    标签: python pandas numpy jupyter-notebook jupyter


    【解决方案1】:

    也许先过滤数据会更容易。我不确定您是否特别想使用.where(),但如果不是,这也将有助于您下一步添加更多条件。

    另外,我认为您的部分问题是在您的 df 中,col2 值是字符串,因此您需要让您的公式找到“4”而不是数字 4。

    df.loc[df['col2'] == '4','col1'].sample(n=2)
    

    【讨论】:

    • 对于附加条件,我将使用以下代码:df.loc[(df['col2'] == '4') & (df['col3'] == 'Sweden'),'col1'].sample(n=2)
    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    相关资源
    最近更新 更多