Dave
Dave

Reputation: 21

How do you export a dataframe to an exisiting, formatted csv file?

I'm trying to export a dataframe to an exisiting,formatted csv file but the dataframe keeps on getting appended in a vertical form along with additional headers which should horizontal.

A B C D E F
1 2 3 4 5 6   #=-> This is the format I have in my exisiting csv file

A B C D E F
1 2 3 4 5 6
x x x x x x   #-> This is how I want to do it

A B C D E F
1 2 3 4 5 6
A 1
B 2
C 3 
D 4  #-> This is what's currently happening

Any help would be much appreciated. Thank you!

df.iloc[location].to_csv(path,mode='a')

This is the code that I've been trying with.

Upvotes: 2

Views: 63

Answers (3)

Derek Eden
Derek Eden

Reputation: 4638

df.iloc[location].T.to_csv('filename.csv',mode='a',index=False,header=False)

Upvotes: 0

furas
furas

Reputation: 143216

df.iloc[location] can gives you Series which is treated different then DataFrame

You would have to convert it to DataFrame but using list with this Series to get data in row instead of column

df = pd.DataFrame( [df.iloc[location]] )

and then save to csv without header

df.to_csv(path, mode='a', header=None)

EDIT: you can also convert Series to DataFrame using .to_frame() and then use .T to transpose column to row

df = df.iloc[location].to_frame().T

Upvotes: 4

Elias Kassell
Elias Kassell

Reputation: 180

The situation you want this to happen in is unclear, but one good generic method is to

df1 = pd.read_csv(...)      # Read the file.
df2 = pd.DataFrame(...)     # Make a DataFrame of the new entries you want to add.
df = pd.concat([df1, df2])  # Concatenate the two.
df.to_csv(...)              # Write the file to the original directory.

Upvotes: 2

Related Questions