We have a multi-index DataFrame df
0 1 2
Name Stock
Tom AAPL 0 0 0
GOOG 0 0 0
NFLX 0 0 0
John AAPL 0 0 0
GOOG 0 0 0
NFLX 0 0 0
and a Series s
AAPL 99
NFLX 11
dtype: int64
Question: How can we set the values in column 2 of the dataframe df using values from the series s?
In other words, only the values for index ('Tom', 'AAPL') and ('Tom', 'NFLX) in dataframe df should be set to 99 and 11, respectively. ('Tom', 'GOOG') should remain unchanged.
Failed Attempt
idx = pd.IndexSlice
df.loc[idx['Tom', :], 2] = s
print(df)
0 1 2
Name Stock
Tom AAPL 0 0 NaN
GOOG 0 0 NaN
NFLX 0 0 NaN
John AAPL 0 0 0.0
GOOG 0 0 0.0
NFLX 0 0 0.0
Code to Reproduce Problem
stocks = ['AAPL', 'GOOG', 'NFLX']
names = ['Tom', 'John']
midx = pd.MultiIndex.from_product([names, stocks], names=['Name','Stock'])
df = pd.DataFrame(index=midx)
for i in range(3):
df[i] = [0,0,0,0,0,0]
print(df)
s = pd.Series([99, 11], index=['AAPL','NFLX'])
print('\n', s, '\n')
idx = pd.IndexSlice
df.loc[idx['Tom', :], 2] = s
print(df)
John, AAPLandJohn, NFLX, shouldn't these be changed as well?Tom, which I attempted to specify usingdf.loc[idx['Tom', :], 2] = s