Redman
Redman

Reputation: 39

Accessing cell in pandas dataframe

I have the following empty dataframe:

ds = ['ds1' ,' ds2', 'ds3']
cl = ['cl1', 'cl2', 'cl3']
re = ['re1', 're2', 're3', 're4']
rows = pd.MultiIndex.from_product([ds, cl, re])

ro = [1,2,3]
fo = [1,2,3,4,5]
cols = pd.MultiIndex.from_product([ro, fo])

df = pd.DataFrame(data=None, index=rows, columns=cols)

I am now trying to populate the first cell using the following code:

somevalue = 42
df[1, 1]['ds1', 'cl1', 're1'] = somevalue

No errors are being thrown up but the df is not being populated. How else can I populate the dataframe?

Upvotes: 1

Views: 789

Answers (1)

piRSquared
piRSquared

Reputation: 294288

Use df.at for single cell assignment.

df.at[('ds1', 'cl1', 're1'), (1, 1)] = somevalue

You can also use loc but is not as quick for use on single cells.

df.loc[('ds1', 'cl1', 're1'), (1, 1)] = somevalue

Upvotes: 3

Related Questions