WJA
WJA

Reputation: 7004

How do I overwrite the value of a specific index/column in a DataFrame?

I have a dataframe Exposure with zeros constructed as follows:

Exposure = pd.DataFrame(0, index=dates, columns=tickers)

and a DataFrame df with data.

I want to fill some of the data from df to Exposure:

    for index, column in df.iterrows():
        # value of df(index,column) to be filled at Exposure(index,column)

How do I overwrite the value of at (index,column) of Exposure with the value of df(index,column)?

Upvotes: 1

Views: 4880

Answers (2)

akuiper
akuiper

Reputation: 214957

You can try this:

for index, column in df.iterrows():
    Exposure.loc[index, column.index] = column.values

This will make new index and columns in Exposure if they don't exist, if you want to avoid this, construct the common index and columns firstly, then do the assignment in a vectorized way(avoiding the for loop):

common_index = Exposure.index.intersection(df.index)
common_columns = Exposure.columns.intersection(df.columns)
Exposure.loc[common_index, common_columns] = df.loc[common_index, common_columns]

Upvotes: 1

Batman
Batman

Reputation: 8927

The best way is:

df.loc[index, column] = value

Upvotes: 3

Related Questions