Home > database >  Pandas load data frame in to txt file with column value pair
Pandas load data frame in to txt file with column value pair

Time:10-19

I have loaded csv file into pandas data frame and it looks like below example

   c1   c2   c3
0  12   22   66
1  44   78   AB
2  DF   WE   13

I want this data frame to be loaded in a .txt file with below format

c1="12",c2="22",c3="66"
c1="44",c2="78",c3="AB"
c1="DF",c2="WE",c3="13"

Each row should be on new line in the text file. Please help me out to find out how it can be done in a best optimal way.

CodePudding user response:

Convert values to strings, append " by DataFrame.add, prepend = by DataFrame.radd and also prepend columns names:

df = df.astype(str).add('"').radd('="').radd(df.columns.to_series())
#alternative
#df = ('="'   df.astype(str)   '"').radd(df.columns.to_series())
print (df)
        c1       c2       c3
0  c1="12"  c2="22"  c3="66"
1  c1="44"  c2="78"  c3="AB"
2  c1="DF"  c2="WE"  c3="13"

And then use DataFrame.to_csv:

import csv

df.to_csv('file.txt', header=None, index=False, quoting=csv.QUOTE_NONE)

c1="12",c2="22",c3="66"
c1="44",c2="78",c3="AB"
c1="DF",c2="WE",c3="13"
  • Related