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>Using pandas, this translates to:</p>

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

<p>You can splice the dataframe later to choose what you want.</p>

python csv pandas random