Skip to content Skip to sidebar Skip to footer

Add To A Dataframe As I Go With Datetime Index

I am trying to get it so that as I loop over a list of things I can add into a dataframe the quantity received from each warehouse on a certain date. When I try the following it do

Solution 1:

Say your initial dataframe looks like so:

data = {'InventoryA': [10, np.nan, -5]}
df = pd.DataFrame(data, index=pd.to_datetime(['2017-01-01', '2017-01-03', '2017-01-05']))

Now you want to add a new value (not sure in what you form you want it, but here it's in a dataframe):

new_vals = pd.DataFrame({'InventoryB': 10}, index=pd.to_datetime(['2017-01-02']))

# Add new column if it doesn't exist.if new_vals.columns.values not in df.columns.values:
    df[new_vals.columns.values[0]] = np.nan

# Add new row if it doesn't exist or add value if it does.if new_vals.index not in df.index: 
    df = df.append(new_vals)
else: df.loc[new_vals.index, new_vals.columns] += new_vals

# Sort by datedf = df.sort_index(axis=0)

Post a Comment for "Add To A Dataframe As I Go With Datetime Index"