Search code examples
pythonpandascsvconcatenationseparator

df.to_csv method using pandas does not work well with space as separator


Im trying to export this dataframe to CSV using pandas, with a space as a separator. I do this because I have two dataframes and I want to stack them side by side (horizontally) instead of vertically. I use concat to do this, but exporting to CSV makes python automatically regard them as a single cell. Hence I tried to enforce a space separator (argument sep=" ") when I write it CSV. However the output still ignores the separator and the result is still a single column data. My code is as follows

import pandas as pd
file='RALS-03.csv'
df=pd.read_csv(file
#get two items on two different columns                )
items1=df.iloc[:,0] 
items2=df.iloc[:,4]

#get corresponding numbers for the two columns of items
mar1=df.iloc[:,2]
mar2=df.iloc[:,6]

#stack them vertically
df1=items1.append(items2)
df2=mar1.append(mar2)

#put them side by side 
df4=pd.concat([df1, df2], axis=1)

#write to CSV file, with a space as a separator
df4.to_csv("new.csv", sep=" ")

Any advices? Thx in adv


Solution

  • Use sep= '\t'

    df4.to_csv('new.csv', sep='\t')