Home>
import pandas as pd
import numpy as np
one = pd.read_csv ('data1.csv')
two = pd.read_csv ('data2.csv')
When

and data are read, one is

A Date
10 2011-01-03
20 2011-01-04
10 2011-01-06
20 2011-01-07
30 2011-01-10
40 2011-01-13
25 2011-01-15
・
・
・</Code></pre>
<p>two is</p>
<pre><code>B Date
15 2011-01-01
15 2011-01-02
15 2011-01-03
25 2011-01-07
35 2011-01-10
10 2011-01-13
25 2011-01-15
・
・
・</Code></pre>
<p><br />
It becomes DataFrame like.<br />
I want to make only one and two, the data that is common to both Dates into a one/two DataFrame, and put 0 in the date data that was missing when merging.<br />
Currently</p>
<pre><code>one_and_two = pd.merge (one, two, on = 'Date', how = 'inner')
print (one_and_two)


Write and execute code like

A Date B
0 10 2011-01-03 15
1 20 2011-01-07 25
2 30 2011-01-10 35
3 40 2011-01-13 10
4 25 2011-01-15 25
・
・
・


I got an output like The ideal output is

A Date B
0 0 2011-01-01 15
1 0 2011-01-02 15
2 10 2011-01-03 15
3 20 2011-01-04 0
4 0 2011-01-05 0
5 10 2011-01-06 0
6 20 2011-01-07 25
7 0 2011-01-08 0
8 0 2011-01-09 0
9 30 2011-01-10 35
・
・
・


It is to form like.
For 2011-01-01 to 2011-12-31, I would like to make an ideal data frame by putting 0 in no value.
How can I do that if I write the code?

  • Answer # 1

    If you want to process the Date column as a string

    df = pd.DataFrame ({'Date': pd.date_range ('2011-01-01', '2011-12-31', freq = '1D') .strftime ('% Y-% m-% d')})
    df = one.merge (df, on = 'Date', how = 'right'). fillna (0) .astype ({'A': int})
    df = df.merge (two, on = 'Date', how = 'left'). fillna (0) .astype ({'B': int})


  • Answer # 2

    pd.merge (one, two, on = 'Date', how = 'outer')


    Is n’t it good?