我尝试使用以下代码将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来解决这个问题。谢谢!在
假设你有一个CSV读入pandas:
你可以把它缩短:
^{pr2}$Pandas IO docs有更多可用的信息和选项,
dataframe.sample
方法也是如此。在使用熊猫,这意味着:
您可以稍后拼接数据帧以选择所需内容。在
相关问题 更多 >
编程相关推荐