Create a simple DataFrame.
import numpy as np
import pandas as pd
# Set the seed so that the numbers can be reproduced.
np.random.seed(0)
df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
# Another way to set column names is "columns=['column_1_name','column_2_name','column_3_name']"
df
A B C
0 1.764052 0.400157 0.978738
1 2.240893 1.867558 -0.977278
2 0.950088 -0.151357 -0.103219
3 0.410599 0.144044 1.454274
4 0.761038 0.121675 0.443863
Now, write to a CSV file:
df.to_csv('example.csv', index=False)
Contents of example.csv:
A,B,C
1.76405234597,0.400157208367,0.978737984106
2.2408931992,1.86755799015,-0.977277879876
0.950088417526,-0.151357208298,-0.103218851794
0.410598501938,0.144043571161,1.45427350696
0.761037725147,0.121675016493,0.443863232745
Note that we specify index=False
so that the auto-generated indices (row #s 0,1,2,3,4) are not included in the CSV file. Include it if you need the index column, like so:
df.to_csv('example.csv', index=True) # Or just leave off the index param; default is True
Contents of example.csv:
,A,B,C
0,1.76405234597,0.400157208367,0.978737984106
1,2.2408931992,1.86755799015,-0.977277879876
2,0.950088417526,-0.151357208298,-0.103218851794
3,0.410598501938,0.144043571161,1.45427350696
4,0.761037725147,0.121675016493,0.443863232745
Also note that you can remove the header if it's not needed with header=False
. This is the simplest output:
df.to_csv('example.csv', index=False, header=False)
Contents of example.csv:
1.76405234597,0.400157208367,0.978737984106
2.2408931992,1.86755799015,-0.977277879876
0.950088417526,-0.151357208298,-0.103218851794
0.410598501938,0.144043571161,1.45427350696
0.761037725147,0.121675016493,0.443863232745
The delimiter can be set by sep=
argument, although the standard separator for csv files is ','
.
df.to_csv('example.csv', index=False, header=False, sep='\t')
1.76405234597 0.400157208367 0.978737984106
2.2408931992 1.86755799015 -0.977277879876
0.950088417526 -0.151357208298 -0.103218851794
0.410598501938 0.144043571161 1.45427350696
0.761037725147 0.121675016493 0.443863232745