I have two dataframes
, both indexed by timeseries
. I need to add the elements together to form a new dataframe
, but only if the index and column are the same. If the item does not exist in one of the dataframe
s then it should be treated as a zero.
I've tried using .add
but this sums regardless of index and column. Also tried a simple combined_data = dataframe1 + dataframe2
but this give a NaN
if both dataframes don't have the element.
Any suggestions?
You can merge a mult-indexed Series and a DataFrame, if the names of the MultiIndex correspond to the columns from the DataFrame. Transform the Series to a DataFrame using Series. reset_index() before merging, as shown in the following example.
append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value. ignore_index : If True, do not use the index labels.
How about x.add(y, fill_value=0)
?
import pandas as pd df1 = pd.DataFrame([(1,2),(3,4),(5,6)], columns=['a','b']) Out: a b 0 1 2 1 3 4 2 5 6 df2 = pd.DataFrame([(100,200),(300,400),(500,600)], columns=['a','b']) Out: a b 0 100 200 1 300 400 2 500 600 df_add = df1.add(df2, fill_value=0) Out: a b 0 101 202 1 303 404 2 505 606
If I understand you correctly, you want something like:
(x.reindex_like(y).fillna(0) + y.fillna(0).fillna(0))
This will give the sum of the two dataframes. If a value is in one dataframe and not the other, the result at that position will be that existing value (look at B0 in X and B0 in Y and look at final output). If a value is missing in both dataframes, the result at that position will be zero (look at B1 in X and B1 in Y and look at final output).
>>> x A B C 0 1 2 NaN 1 3 NaN 4 >>> y A B C 0 8 NaN 88 1 2 NaN 5 2 10 11 12 >>> (x.reindex_like(y).fillna(0) + y.fillna(0).fillna(0)) A B C 0 9 2 88 1 5 0 9 2 10 11 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With