Too many values to unpack (expected 3) error when splitting a column
When using the split method for DataFrame Views, an error occurs: too many values to unpack (expected 3). The task is to split the Date column into 3 columns year, month, day, and then translate it into a date. What am I doing wrong, please tell me? Code:
year, month, day = views.Date.str.split('/')
1
Author: Denis Novik, 2017-01-25
1 answers
Answering your question about .str.split(...)
:
In .str.split(..., expand=False)
by default expand=False
, i.e. it will return pandas.Series
where the elements will be lists:
In [49]: df.date.str.split('/')
Out[49]:
0 [2016, 01, 09]
1 [2016, 11, 11]
2 [2016, 12, 30]
Name: date, dtype: object
If you specify expand=True
, it returns pandas.DataFrame
:
In [50]: df.date.str.split('/', expand=True)
Out[50]:
0 1 2
0 2016 01 09
1 2016 11 11
2 2016 12 30
You can also use .str.extract()
and specify the column names:
In [51]: df.date.str.extract(r'(?P<year>\d{4})[-/\.](?P<month>\d{2})[-/\.](?P<day>\d{2})', expand=True)
Out[51]:
year month day
0 2016 01 09
1 2016 11 11
2 2016 12 30
In [52]: split = df.date.str.extract(r'(?P<year>\d{4})[-/\.](?P<month>\d{2})[-/\.](?P<day>\d{2})', expand=True)
In [53]: split
Out[53]:
year month day
0 2016 01 09
1 2016 11 11
2 2016 12 30
2
Author: MaxU, 2017-01-25 11:11:25