【问题标题】:Randomly Select Rows in Pandas DataFrame Vectorized Operation在 Pandas DataFrame 向量化操作中随机选择行
【发布时间】:2019-08-19 10:46:24
【问题描述】:

我想在 DataFrame 上的向量操作期间选择一个随机行。这就是我的inpDF 的样子:

    string1    string2
0   abc        dfe
1   ghi        jkl
2   mno        pqr
3   stu        vwx

我正在尝试在这里找到函数getRandomRow()

outDF['string1'] = inpDF['string1']
outDF['string2'] = inpDF.getRandomRow()['string2']

所以outDF 最终看起来(例如)像这样:

    string1    string2
0   abc        jkl
1   ghi        pqr
2   mno        dfe
3   stu        pqr

编辑 1:

我尝试按照this answer 中的建议使用sample() 函数,但这只会导致在所有行中复制相同的样本:

outDF['string1'] = inpDF['string1']
outDF['string2'] = inpDF.sample(n=1).iloc[0,:]['string2']

给出:

    string1    string2
0   abc        pqr
1   ghi        pqr
2   mno        pqr
3   stu        pqr

编辑 2:

对于我的特定用例,即使从“n”行中选择值也足够了。所以,我尝试这样做(根据我在this answer 中读到的内容,我使用inpDF.index):

numRows = len(inpDF)

outDF['string1'] = inpDF['string1']
outDF['string2'] = inpDF.iloc[(inpDF.index + 2)%numRows,:]['string2']

但它只是从同一行中选择值,outDF 是这样的:

    string1    string2
0   abc        dfe
1   ghi        jkl
2   mno        pqr
3   stu        vwx

而我期望它应该是这样的:

    string1    string2
0   abc        pqr
1   ghi        vwx
2   mno        dfe
3   stu        jkl

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您为此使用pandas.DataFrame.sample

    df['string2'] = df.string2.sample(len(df.string2)).to_list()
    
    print(df)
      string1 string2
    0     abc     vwx
    1     ghi     jkl
    2     mno     def
    3     stu     pqr
    

    或者

    df['string2'] = df.string2.sample(len(df.string2)).values
    

    【讨论】:

    • 如果我不添加to_list()values,我会从该行中获得未打乱的值...这是为什么呢?
    • pandas 中可能有点令人困惑,但我们可以参考带有括号的列:df['string2'] 或像 df.string2 这样的点符号。两者都是一样的。这是你喜欢的@shinvu
    • Goed question @shinvu 我在回答您的问题时自己也在想这个问题。我刚刚发布了这是一个新问题,你可以在这里关注它:stackoverflow.com/questions/55401864/…
    【解决方案2】:

    试试np.random.shuffle():

    np.random.shuffle(df.string2)
    print(df)
    
      string1 string2
    0     abc     pqr
    1     ghi     vwx
    2     mno     def
    3     stu     jkl
    

    如果您不想就地随机播放,请尝试:

    df['string3']=np.random.permutation(df.string2)
    print(df)
    

    【讨论】:

    • np.random.shuffle +1 的好答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2019-01-15
    • 2021-01-04
    • 1970-01-01
    • 2019-05-24
    相关资源
    最近更新 更多