【问题标题】:Pandas shuffle column values doesn't workPandas shuffle 列值不起作用
【发布时间】:2017-06-19 19:42:48
【问题描述】:

我有 2 列的 csv:“上下文”、“话语”。

我需要洗牌(随机排序)“上下文”列值。注意,不是整行洗牌,而是只有1列,第二列“话语”顺序保持不变。

为此我使用了:answers (shuffling/permutating a DataFrame in pandas)

  train_df2 = pd.read_csv("./data/nolabel.csv", encoding='utf-8', sep=",")
  train_df2.drop('Utterance', axis=1, inplace=True) # delete 'Utterance'
  train_df2 = train_df2.sample(frac=1) # shuffle
  train_df2['Utterance'] = train_moscow_df['Utterance'] # add back 'Utterance'
  train_df2["Label"] = 0 
  header = ["Context", "Utterance", "Label"] # 

  train_df2.to_csv('./data/label0.csv', columns = header, encoding='utf-8', index = False)

但是,结果很糟糕:我得到了一个完整的行 shuffle,但 2 列的相应值仍然相同。

我需要第一列的第一个值对应于第二列的随机值。 (也尝试过from sklearn.utils import shuffle,但也没有运气)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    问题是,当 df 被打乱时,索引被打乱,但是你将原始列添加回来,它会在原始索引上对齐,你可以调用reset_index,这样它就不会这样做:

    train_df2 = train_df2.sample(frac=1) # shuffle
    train_df2.reset_index(inplace=True, drop=True)
    train_df2['Utterance'] = train_moscow_df['Utterance'] # add back 'Utterance'
    

    例子:

    In [196]:
    # setup
    df = pd.DataFrame(np.random.randn(5,2), columns=list('ab'))
    df
    
    Out[196]:
              a         b
    0  0.116596 -0.684748
    1 -0.133922 -0.969933
    2  0.103551  0.912101
    3 -0.279751 -0.348443
    4  1.453413  0.062378
    

    现在我们像以前一样丢弃和洗牌,注意索引值

    In [197]:
    a = df.drop('b', axis=1)
    a = a.sample(frac=1)
    a
    
    Out[197]:
              a
    3 -0.279751
    0  0.116596
    1 -0.133922
    4  1.453413
    2  0.103551
    

    现在重置

    In [198]:    
    a.reset_index(inplace=True, drop=True)
    a
    
    Out[198]:
              a
    0 -0.279751
    1  0.116596
    2 -0.133922
    3  1.453413
    4  0.103551
    

    我们可以将列添加回来,但保留打乱顺序:

    In [199]:
    df['b'] = a['b']
    df
    
    Out[199]:
              a         b
    0 -0.279751 -0.684748
    1  0.116596 -0.969933
    2 -0.133922  0.912101
    3  1.453413 -0.348443
    4  0.103551  0.062378
    

    【讨论】:

    • 最后一行应该是df['b'] = a['b']
    • @KubiK888 确实,会更新,谢谢告知
    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 2020-08-18
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多