I am currently using Python and Pandas to form a stock price "database". I managed to find some codes to download the stock prices.
df1 is my existing database. Each time I download the share price, it will look like df2 and df3. Then, i need to combine df1, df2 and df3 data to look like df4.
Each stock has its own column. Each date has its own row.
df1: Existing database
+----------+-------+----------+--------+
| Date | Apple | Facebook | Google |
+----------+-------+----------+--------+
| 1/1/2018 | 161 | 58 | 1000 |
| 2/1/2018 | 170 | 80 | |
| 3/1/2018 | 190 | 84 | 100 |
+----------+-------+----------+--------+
df2: New data (2/1/2018 and 4/1/2018) and updated data (3/1/2018) for Google.
+----------+--------+
| Date | Google |
+----------+--------+
| 2/1/2018 | 500 |
| 3/1/2018 | 300 |
| 4/1/2018 | 200 |
+----------+--------+
df3: New data for Amazon
+----------+--------+
| Date | Amazon |
+----------+--------+
| 1/1/2018 | 1000 |
| 2/1/2018 | 1500 |
| 3/1/2018 | 2000 |
| 4/1/2018 | 3000 |
+----------+--------+
df4 Final output: Basically, it merges and updates all the data into the database. (df1 + df2 + df3) --> this will be the updated database of df1
+----------+-------+----------+--------+--------+
| Date | Apple | Facebook | Google | Amazon |
+----------+-------+----------+--------+--------+
| 1/1/2018 | 161 | 58 | 1000 | 1000 |
| 2/1/2018 | 170 | 80 | 500 | 1500 |
| 3/1/2018 | 190 | 84 | 300 | 2000 |
| 4/1/2018 | | | 200 | 3000 |
+----------+-------+----------+--------+--------+
I do not know how to combine df1 and df3.
And I do not know how to combine df1 and df2 (add new row: 4/1/2018) while at the same time updating the data (2/1/2018 -> Original data: NaN; amended data: 500 | 3/1/2018 -> Original data: 100; amended data: 300) and leaving the existing intact data (1/1/2018).
Can anyone help me to get df4? =)
Thank you.
EDIT: Based on Sociopath suggestion, I amended the code to:
dataframes = [df2, df3]
df4 = df1
for i in dataframes:
# Merge the dataframe
df4 = df4.merge(i, how='outer', on='date')
# Get the stock name
stock_name = i.columns[1]
# To check if there is any column with "_x", if have, then combine these columns
if stock_name+"_x" in df4.columns:
x = stock_name+"_x"
y = stock_name+"_y"
df4[stock_name] = df4[y].fillna(df4[x])
df4.drop([x, y], 1, inplace=True)