Kurt Peek
Kurt Peek

Reputation: 57541

Succinct way to access a single value from a Pandas DataFrame by index

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?

Upvotes: 2

Views: 186

Answers (3)

user2285236
user2285236

Reputation:

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

Upvotes: 1

jezrael
jezrael

Reputation: 862851

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

Upvotes: 2

EdChum
EdChum

Reputation: 394099

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

Upvotes: 2

Related Questions