OlavT
OlavT

Reputation: 2666

How to format pandas dataframe when writing to csv file?

I have a Pandas dataframe with the following data

0 5
1 7
2 3

The first column is the index.

What is the easiest way to get this written to a csv file (space delimited) so the output will look like this?

|index 0 |features 5
|index 1 |features 7
|index 2 |features 3

By csv file, I mean writing a file like this:

test.to_csv('test_map2.txt', sep=' ', header=None, index=False)

Upvotes: 1

Views: 5892

Answers (2)

Yonas Kassa
Yonas Kassa

Reputation: 3720

you can proceed as follows

test.index = test.index.map(lambda x:"|index " + str(x))
test.ix[:,0] = test.ix[:,0].apply(lambda x:'|features ' + str(x))
test.to_csv('test_map2.txt', sep=' ', header=None, index=False)

Upvotes: 1

oliversm
oliversm

Reputation: 1977

To have the index as an implicit column in the csv:

import pandas as pd
import io
df = pd.DataFrame(dict(data=[5, 7, 3]))
with io.open('df.csv', 'wb') as file: df.to_csv(file, header=False)

gives

0,5
1,7
2,3

or if you have more interesting index values then use

import pandas as pd
import io
df = pd.DataFrame(dict(data=[5, 7, 3]))
df.reset_index(inplace=True)
with io.open('df.csv', 'wb') as file: df.to_csv(file)

which gives

,index,data
0,0,5
1,1,7
2,2,3

to get spaces the use

import pandas as pd
import io
df = pd.DataFrame(dict(data=[5, 7, 3]))
df.index.rename
with io.open('df.csv', 'wb') as file: df.to_csv(file, sep=" ", header=False)

which gives

0 5
1 7
2 3

although spaces are probably best to avoid.

The closer resemblance to your |header is perhaps

import pandas as pd
import io
df = pd.DataFrame(dict(data=[5, 7, 3]))
df.index.rename
df.reset_index(inplace=True)
for col in df.columns:
    df[col] = df[col].apply(lambda x: '|' +  col + ' ' + str(x))
with io.open('df.csv', 'wb') as file: df.to_csv(file, sep=" ", header=False, index=False, quotechar=' ')

giving

 |index  0   |data  5 
 |index  1   |data  7 
 |index  2   |data  3 

Upvotes: 0

Related Questions