1

This is the sample of my code when I write the dataframe into csv, 9 October 1937 and 81 years ago (1937-10-09) are coming in different columns.

import pandas as pd
df = pd.DataFrame({'established':['9 October 1937, 81 years ago (1937-10-09)','1996'],'location':['hyd','Delhi']})
df.to_csv('some_file.csv')

How to make 9 October 1937, 81 years ago (1937-10-09) should be coming in same column?? Thanks

4
  • Your code works as intended without any changes for me (Windows 7, Python 3.6.4, Pandas 0.22.0). Commented Nov 28, 2018 at 12:05
  • It works fine on my system Commented Nov 28, 2018 at 12:05
  • You need to look into which csv dialect you want to target - one way or another you need to escape, or quote-surround that embedded comma, or some readers will interpret it as a delimiter. Another option would be to force some alternative delimiter - but this is normally considered bad form - it's a faster alternative (if you can control the config of the downstream reader) but generally better to solve using the former mechanism. Commented Nov 28, 2018 at 12:07
  • Thanks @ThomasKimber, it was because some configuration in my csv reader. Its working fine now. Commented Nov 28, 2018 at 12:33

1 Answer 1

1

This works as it should, if you open the file in a plain text reader:

,established,location
0,"9 October 1937, 81 years ago (1937-10-09)",hyd
1,1996,Delhi

You may run into trouble when reading the .csv file afterwards, depending on how your reader handles the "," after 1937. It may understand it either as a field separator and cut right after, or understand that the encompassing quotes " ... " suggest that it is a single field.

To avoid any trouble you may want to use a semi-colon separator when writing the file: df.to_csv("some_file.csv", sep=";")

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.