【问题标题】:Randomising 2 CSV files随机化 2 个 CSV 文件
【发布时间】:2019-06-04 06:13:16
【问题描述】:

我想使用 python 作为 1 对 1 函数同时随机化两个 CSV 文件,即。

File1.csv.                  File2.csv
1.                                A
2.                                B
3.                                C
4.                                D
5.                                E

输出将是

File1.csv.                 File2.csv
4.                               D
1.                               A
3.                               C
5.                               E
2.                               B

【问题讨论】:

  • csv 文件中是否只有一列?你能更准确地描述你的问题吗?
  • 我的 CSV 文件中有多个列。有两个相互关联的不同 CSV 文件。因此,如果对一个 CSV 进行任何更改,我希望它们反映到另一个也是。

标签: python csv random shuffle


【解决方案1】:

由于 csv 文件是静态平面文件,因此您不能直接对其进行随机播放。您需要将这两个文件作为 pd Dataframes 读取,将它们都洗牌,然后将它们写入 csvs。代码如下:

df1 = pd.read_csv('datafile1.csv')
df2 = pd.read_csv('datafile2.csv')

# reset the index by row numbers, so that both dataframe has identical index
df1.reset_index(inplace=True)
df2.reset_index(inplace=True)

#Shuffle the rows
df1 = df1.sample(frac=1) # frac says what fraction of rows shall be returned, 1 means return all rows. This will ensure that all rows are shuffled randomly 
df2 = df2.loc[df1.index] # Since I am using index of df1 to order df2, I am ensuring same order 

# Put back the original indes
df1.set_index('index',drop=True, inplace=True)
df2.set_index('index',drop=True, inplace=True)

# Write back to original files
df1.to_csv('datafile1.csv')
df2.to_csv('datafile2.csv')

【讨论】:

  • 乐于助人:)
【解决方案2】:

尝试使用numpy.random.shuffle wiki 例如:

import numpy as np

letters = ["A","B","C","D","E"]
numbers = [1,2,3,4,5,6]
np.random.shuffle(letters)
print(letters)
np.random.shuffle(numbers)
print(numbers)

输出在这里:

['A', 'C', 'B', 'E', 'D']
[2, 6, 4, 1, 5, 3]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2020-04-01
    • 2021-11-06
    相关资源
    最近更新 更多