python - Pandas 洗牌列值不起作用

标签 python pandas dataframe

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

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

为此我使用了:答案(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)

但是,结果很糟糕:我进行了整行随机播放,但 2 列的相应值仍然相同。

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

最佳答案

问题是,当 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

关于python - Pandas 洗牌列值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42007247/

相关文章:

r - 如何使用 lower.tri 中的匹配整数填充矩阵的 upper.tri?

python - 在 Pandas 中添加数据框

python - Outlook/Python : Open specific message at screen

python - 为什么 Python pandas 将任意时间信息分配给 datetime 对象?

python 多索引赋值

python - Panda AssertionError 列已传递,传递的数据有 2 列

python - 属性错误: 'PGDialect_psycopg2' object has no attribute 'dbapi_type_map'

python - pygame.error : video system not initialized when trying to run examples

python - 如何使饼图标签与数据框中的正确值保持一致?

r - 在数据框中结转的上次观察结果?