Exporting a random sample from CSV file to a new CSV file - output is messy
<p>I am trying to export a random subset of a CSV file to a new CSV file using the following code:</p>

<pre><code>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))
</code></pre>

<p>But the problem is that the output CSV file is very messy. for example, some part of a data in a filed was printed in the next line. How can I solve the problem? In addition, I want to know how can I use pandas for this problem rather than CSV. Thanks !</p>

<p>Assuming you had a CSV read into pandas:</p>

<pre><code>df = pandas.read_csv("csvfile.csv")
sample = df.sample(n)
sample.to_csv("sample.csv")
</code></pre>

<p>You could make it even shorter:</p>

<pre><code>df.sample(n).to_csv("csvfile.csv")
</code></pre>

<p>The <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-store-in-csv" rel="nofollow">Pandas IO docs</a> have a great deal more information and options available, as does the <code>dataframe.sample</code> method.</p>

python csv pandas random