How to change .csv file to .dat file using pandas?

For example, a csv file looks like this: csv content . How to change it to a .dat file like this using '|':

a 1 | b 2 | c 3 | d 4 | ...
a 2 | b 3 | c 4 | d 5 | ...
a 3 | b 4 | c 5 | d 6 | ...
...

+3


source to share


2 answers


Consider a data block df

df = pd.DataFrame([
    [1, 2, 3, 4],
    [2, 3, 4, 5],
    [3, 4, 5, 6]
], columns=list('abcd'))

   a  b  c  d
0  1  2  3  4
1  2  3  4  5
2  3  4  5  6

      


IIUC



df.astype(str).radd(
    df.columns.to_series() + ' '
).to_csv('test.data', header=None, index=None, sep='|')

      


cat test.data

a 1|b 2|c 3|d 4
a 2|b 3|c 4|d 5
a 3|b 4|c 5|d 6

      

+1


source


If df

is your dataframe, do

import pandas
df.to_csv("output.dat", sep = "|")

      

You can check the docs for more settings and information.



(If you haven't read the csv file in pandas yet, this is easy:

df = pandas.read_csv("input.csv")

      

+1


source







All Articles