4

There is a question on SO with the title "Set value for particular cell in pandas DataFrame", but it assumes the row index is known. How do I change a value, if the row values in the relevant column are unique? Is using set_index as below the easiest option? Returning a list of index values with index.tolist does not seem like a very elegant solution.

Here is my code:

import pandas as pd

## Fill the data frame.
df = pd.DataFrame([[1, 2], [3, 4]], columns=('a', 'b'))
print(df, end='\n\n')

## Just use the index, if we know it.
index = 0
df.set_value(index, 'a', 5)
print('set_value', df, sep='\n', end='\n\n')

## Define a new index column.
df.set_index('a', inplace=True)
print('set_index', df, sep='\n', end='\n\n')

## Use the index values of column A, which are known to us.
index = 3
df.set_value(index, 'b', 6)
print('set_value', df, sep='\n', end='\n\n')

## Reset the index.
df.reset_index(inplace = True)
print('reset_index', df, sep='\n')

Here is my output:

   a  b
0  1  2
1  3  4

set_value
   a  b
0  5  2
1  3  4

set_index
   b
a   
5  2
3  4

set_value
   b
a   
5  2
3  6

reset_index
   a  b
0  5  2
1  3  6
tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108

1 Answers1

9

Regardless of the performance, you should be able to do this using loc with boolean indexing:

df = pd.DataFrame([[5, 2], [3, 4]], columns=('a', 'b'))

# modify value in column b where a is 3
df.loc[df.a == 3, 'b'] = 6

df
#   a   b
#0  5   2
#1  3   6
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Thanks! I found the same answer in the other question thread just now. It just had very few votes. https://stackoverflow.com/a/38467449/778533 – tommy.carstensen May 27 '17 at 14:41
  • @tommy.carstensen It's a very recent answer, almost four years after the question was first asked. :) – Psidom May 27 '17 at 14:43