9951 explained code solutions for 126 technologies


python-pandasHow to export dataframe to CSV


import pandas as pd

df = pd.DataFrame(
  {
    "A": 1.0,
    "B": pd.Timestamp("20220102"),
    "C": pd.Series(1, index=list(range(4)), dtype="float32"),
    "E": pd.Categorical(["test", "first", "test", "second"]),
    "F": "foo"
  }
)

df.to_csv('/tmp/data.csv')ctrl + c
import pandas as pd

load Pandas module

pd.DataFrame

creates Pandas DataFrame object

.to_csv

saves DataFrame to the specified CSV file

/tmp/data.csv

path to CSV file to save data to


Usage example

import pandas as pd

df = pd.DataFrame(
  {
    "A": 1.0,
    "B": pd.Timestamp("20220102"),
    "C": pd.Series(1, index=list(range(4)), dtype="float32"),
    "E": pd.Categorical(["test", "first", "test", "second"]),
    "F": "foo"
  }
)

df.to_csv('/tmp/data.csv')

with open('/tmp/data.csv', 'r') as f:
  print(f.read())
output
,A,B,C,E,F
0,1.0,2022-01-02,1.0,test,foo
1,1.0,2022-01-02,1.0,first,foo
2,1.0,2022-01-02,1.0,test,foo
3,1.0,2022-01-02,1.0,second,foo