Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

python - reindex to add missing dates to pandas dataframe

I try to parse a CSV file which looks like this:

dd.mm.yyyy   value

01.01.2000   1
02.01.2000   2
01.02.2000   3

I need to add missing dates and fill according values with NaN. I used Series.reindex like in this question:

import pandas as pd

ts=pd.read_csv(file, sep=';', parse_dates='True', index_col=0)

idx = pd.date_range('01.01.2000', '02.01.2000')

ts.index = pd.DatetimeIndex(ts.index)
ts = ts.reindex(idx, fill_value='NaN')

But in result, values for certain dates are swapped due to date format (i.e. mm/dd instead of dd/mm):

01.01.2000   1
02.01.2000   3
03.01.2000   NaN
...
...
31.01.2000   NaN
01.02.2000   2

I tried several ways (i.e. add dayfirst=True to read_csv) to do it right but still can't figure it out. Please, help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set parse_dates to the first column with parse_dates=[0]:

ts = pd.read_csv(file, sep=';', parse_dates=[0], index_col=0, dayfirst=True)

idx = pd.date_range('01.01.2000', '02.01.2000')

ts.index = pd.DatetimeIndex(ts.index)
ts = ts.reindex(idx, fill_value='NaN')
print(ts)

prints:

              value
2000-01-01        1
2000-01-02        2
2000-01-03      NaN
...
2000-01-31      NaN
2000-02-01        3

parse_dates=[0] tells pandas to explicitly parse the first column as dates. From the docs:

parse_dates : boolean, list of ints or names, list of lists, or dict

If True -> try parsing the index.

If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.

If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.

{'foo' : [1, 3]} -> parse columns 1, 3 as date and call result 'foo'

A fast-path exists for iso8601-formatted dates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...