3

First, I create a pandas dataframe from a .csv file:

df1 = pd.read_csv(infile1, sep=",", usecols=cols, header=0, names=["Timestamp","x"])

Second, I do print df1.head() which produces:

       Timestamp      x
0  1491894899989  15424
1  1491894899984  15424
2  1491894899979  15488
3  1491894899974  15488
4  1491894899969  15488

Then, doing print int(df1.x.iloc[[0]].values) yields 15424.

Now, I want to replace the iloc[[0]] value for x.

The line df1.x.iloc[[0]].values == 88 does not do the trick, since print int(df1.x.iloc[[0]].values) still yields 15424 rather than 88.

How to replace the value in the nth row of a given column in a pandas dataframe?

sudonym
  • 3,788
  • 4
  • 36
  • 61
  • There are a number of ways to assign a value at a particular cell. See https://stackoverflow.com/a/43968774/190597. – unutbu Jun 21 '17 at 16:56

1 Answers1

5

Try replacing the double equals sign (the comparison operator) with a single equals sign (the assignment operator):

df1.x.iloc[[0]].values = 88

Side note: in my testing, it is not necessary to wrap the row index 0 in list brackets in this case, nor is it necessary to assign the new value to .values. I get the same result as the line above with this:

df1.x.iloc[0] = 88

Maybe someone with more pandas experience can weigh in.

Runnable test case:

import pandas as pd
import numpy as np
df = pd.DataFrame({'col1': ['asdf']*5})
df.col1.iloc[0] = 'jkl'
df
#    output:
#       col1
#    0   jkl
#    1  asdf
#    2  asdf
#    3  asdf
#    4  asdf
Peter Leimbigler
  • 10,775
  • 1
  • 23
  • 37