'How to split one string element in a list into two in Python?
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?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | richardec |
