2

Suppose I have a DataFrame generated like so:

import numpy as np
import pandas as pd

np.random.seed(seed=0)
df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2))

which looks like

          C         D
A  1.764052  0.400157
B  0.978738  2.240893

and suppose I'd like to increase the value in row A, column C by 1. The way I've found to do this is:

df['C'][df.index.isin(['A'])] += 1

The left hand side seems quite verbose; I was hoping there might be a shorter way to do this?

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526

3 Answers3

3

You can use loc directly on the col:

In [298]:
df['C'].loc['A'] += 1
df

Out[298]:
          C         D
A  2.764052  0.400157
B  0.978738  2.240893

or compound it by passing the row label as first arg on the df and select the col of interest after the comma:

In [300]:
df.loc['A','C'] += 1
df

Out[300]:
          C         D
A  2.764052  0.400157
B  0.978738  2.240893
EdChum
  • 376,765
  • 198
  • 813
  • 562
2

Use ix:

np.random.seed(seed=0)
df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2))

df.ix['A','C'] += 1
print (df)
          C         D
A  2.764052  0.400157
B  0.978738  2.240893
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

You can use .at for accessing/setting scalars. Take a look at this answer for a comparison of them.

df
Out: 
          C         D
A  1.764052  0.400157
B  0.978738  2.240893

df.at['A', 'C'] += 1

df
Out: 
          C         D
A  2.764052  0.400157
B  0.978738  2.240893
Community
  • 1
  • 1
ayhan
  • 70,170
  • 20
  • 182
  • 203