I have a data set that includes information about fund daily performance. In my full data set there are daily metrics between 12/1/15 and 6/29/17 but not all of the funds have information for each one of these days.
What I would like to do is add rows for each day between the min and max dates (12/1/15 and 6/29/17) and have N/A values for adjusted close prices.
#ORIGINAL DATASET (EXAMPLE)
# List of Tuples
records = [ ('Fund 1', 34, '12/1/18') ,
('Fund 1', 53, '12/2/18') ,
('Fund 1', 42, '12/3/18') ,
('Fund 2', 44, '12/3/18') ,
('Fund 1', 32, '12/4/18') ,
('Fund 2', 31, '12/4/18') ,
('Fund 2', 57, '12/5/18') ]
#Create a DataFrame object
dfObj = pd.DataFrame(records, columns = ['Fund' , '$', 'Date'])
dfObj
Fund $ Date
Fund 1 34 12/1/18
Fund 1 53 12/2/18
Fund 1 42 12/3/18
Fund 2 44 12/3/18
Fund 1 32 12/4/18
Fund 2 31 12/4/18
Fund 2 57 12/5/18
#DESIRED DATASET (EXAMPLE)
# List of Tuples
desired_records = [ ('Fund 1', 34, '12/1/18') ,
('Fund 1', 53, '12/2/18') ,
('Fund 1', 42, '12/3/18') ,
('Fund 2', 44, '12/3/18') ,
('Fund 1', 32, '12/4/18') ,
('Fund 2', 31, '12/4/18'),
('Fund 2', 0, '12/1/18') ,
('Fund 2', 0, '12/2/18'),
('Fund 2', 57, '12/5/18'),
('Fund 1', 0, '12/5/18') ]
#Create a DataFrame object
desired_df = pd.DataFrame(desired_records, columns = ['Fund' , '$', 'Date'])
desired_df.sort_values(by=['Date'])
Fund $ Date
Fund 1 34 12/1/18
Fund 2 0 12/1/18
Fund 1 53 12/2/18
Fund 2 0 12/2/18
Fund 1 42 12/3/18
Fund 2 44 12/3/18
Fund 1 32 12/4/18
Fund 2 31 12/4/18
Fund 2 57 12/5/18
Fund 1 0 12/5/18
Is this a simple fix?
In your case using stack
and unstack
df=df.set_index(['Date','Fund']).unstack(fill_value=0).stack().reset_index()
Out[138]:
Date Fund $
0 12/1/18 Fund 1 34
1 12/1/18 Fund 2 0
2 12/2/18 Fund 1 53
3 12/2/18 Fund 2 0
4 12/3/18 Fund 1 42
5 12/3/18 Fund 2 44
6 12/4/18 Fund 1 32
7 12/4/18 Fund 2 31
8 12/5/18 Fund 1 0
9 12/5/18 Fund 2 57
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.