Search code examples
pythoncsvexport-to-csv

Converting Comma delimted CSV to Tab delimted CSV in pandas


I am using python I have a CSV file which had values separated by tab, I applied a rule to each of its row and created a new csv file, the resulting dataframe is comma separated , I want this new csv to be tab separated as well. How can I do it ? I understand using sep = '\t' can work but where do I apply it ? I applied the following code but it didn't work either

df = pd.read_csv('data.csv', header=None)
df_norm= df.apply(lambda x:np.where(x>0,x/x.max(),np.where(x<0,-x/x.min(),x)),axis=1)
df_norm.to_csv("file.csv", sep="\t") 

enter image description here

enter image description here

enter image description here


Solution

  • I found the issue, the rule had changed the type to "object', because of which I was unable to perform any further operations. I followed Remove dtype at the end of numpy array, and converted my data frame to a list which solved the issue.

    df = pd.read_csv('data.csv', header=None)
    df_norm= df.apply(lambda x:np.where(x>0,x/x.max(),np.where(x<0,-x/x.min(),x)),axis=1)
    df_norm=df_norm.tolist()
    df_norm = np.squeeze(np.asarray(df_norm))
    np.savetxt('result.csv', df_norm, delimiter=",")