Home > database >  How to split one string element in a list into two in Python?
How to split one string element in a list into two in Python?

Time:03-22

Sorry in advance if this is a silly question.

I need to use pandas to sort some data, but what I have been given is formatted strangely, and I get an error message "2 columns passed, passed data had 1 columns"

['Fred Green,20/11/2020\n', 'Jack Wilson,01/05/2021\n',] etc.

How can I go about splitting the elements into two at the , point, so I can get my columns to work properly?

CodePudding user response:

I'd use list-comprehension to split each string and then pass it to pd.DataFrame:

lst = ['Fred Green,20/11/2020\n', 'Jack Wilson,01/05/2021\n',]

df = pd.DataFrame([item.strip().split(',') for item in lst], columns=['name', 'date'])

Output:

>>> df
          name        date
0   Fred Green  20/11/2020
1  Jack Wilson  01/05/2021
  • Related