Reputation: 95
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
Upvotes: 3
Views: 8034
Reputation: 16
print df1 and df2 before concat. Check their column label and row index, column label cannot be the same. but row index must be the same.
And then use the following to print the result to a file
with open('df_out.txt', 'w') as f:
print(df4, file=f)
Upvotes: 0