Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For example, the csv file looks like this: csv content. How to change it to .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|...
...

like image 866
dlwlrma Avatar asked Dec 03 '25 08:12

dlwlrma


2 Answers

If df is your dataframe, do

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

You can check the docs for more settings and info.

(If you have not read the csv file into pandas yet, it's easy:

df = pandas.read_csv("input.csv")
like image 87
patrick Avatar answered Dec 05 '25 23:12

patrick


Consider the dataframe 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
like image 28
piRSquared Avatar answered Dec 05 '25 21:12

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!