Skip to main content
 首页 » 编程设计

python之Pandas 洗牌列值不起作用

2024年10月01日10TianFang

我有包含 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