建立隨機 DataFrame 並寫入 .csv

建立一個簡單的 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

現在,寫入 CSV 檔案:

df.to_csv('example.csv', index=False)

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

請注意,我們指定 index=False,以便自動生成的索引(行#s 0,1,2,3,4)不包含在 CSV 檔案中。如果需要索引列,請包括它,如下所示:

df.to_csv('example.csv', index=True)  # Or just leave off the index param; default is True

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

另請注意,如果 header=False 不需要,你可以刪除標題。這是最簡單的輸出:

df.to_csv('example.csv', index=False, header=False)

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

分隔符可以通過 sep= 引數設定,儘管 csv 檔案的標準分隔符是','

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