将随机样本从CSV文件导出到新的CSV文件输出很麻烦

2024-10-03 04:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用以下代码将CSV文件的随机子集导出到新的CSV文件:

with open("DepressionEffexor.csv", "r") as effexor:
    lines = [line for line in effexor]
    random_choice = random.sample(lines, 229)

with open("effexorSample.csv", "w") as sample:
   sample.write("\n".join(random_choice))

但问题是输出的CSV文件非常混乱。例如,一个字段中的某部分数据被打印到下一行。我怎么解决这个问题?另外,我想知道如何使用pandas而不是CSV来解决这个问题。谢谢!在


Tags: 文件csvsample代码aswithlinerandom
2条回答

假设你有一个CSV读入pandas:

df = pandas.read_csv("csvfile.csv")
sample = df.sample(n)
sample.to_csv("sample.csv")

你可以把它缩短:

^{pr2}$

Pandas IO docs有更多可用的信息和选项,dataframe.sample方法也是如此。在

使用熊猫,这意味着:

import pandas as pd

#Read the csv file and store it as a dataframe
df = pd.read_csv('DepressionEffexor.csv')

#Shuffle the dataframe and store it
df_shuffled = df.iloc[np.random.permutation(len(df))]

#You can reset the index with the following
df_shuffled.reset_index(drop=True)

您可以稍后拼接数据帧以选择所需内容。在

相关问题 更多 >