0

I'm doing the following to update a dataframe row:

val = "123"
row = df.loc[id, :]
t = type(row['col1'])
val = t(val)
df.loc[id, 'col1'] = val

If I do row['col1'] = val, it doesn't update the original dataframe. Is there a way to update the original dataframe without using .loc twice?

ashic
  • 6,367
  • 5
  • 33
  • 54

1 Answers1

0

Updated for comment below
I believe the short answer is no to

Is there someway of saying "change the row you've already fetched"

This is because operations in Pandas return a copy not a view to the original DataFrame. There is a StackOverflow post from JeffR who writes much of Pandas here

If you're trying to assign the val to one cell in the DataFrame you can use the set_value function. The documentation for that method is here.

val = "123"
row = df.loc[id, :]
t = type(row['col1'])
val = t(val)
df.set_value(id, 'col1', val)

If you're trying to assign the val with particular data type to all cells in column, can use the apply method

def changeType(cell, val):
    # You could pass the id or list of ids as well if you need to perform some logic with it
    t = type(cell)
    cell = t(val)
    return cell

val = "123"
df.loc[:, 'col1'] = df.loc[:, 'col1'].apply(changeType, args=(val,))
Josh
  • 2,767
  • 1
  • 27
  • 31
  • df.loc[:, 'col1'] = val would set it for all rows, right? I only want the row matching id to be updated. set_value looks like it'll do what I need, but wouldn't it still require another lookup? Is there someway of saying "change the row you've already fetched", instead of "find row with this id, and change it"? – ashic Aug 08 '17 at 14:42
  • I've updated my answer, I better understand what you were trying to ask. – Josh Aug 08 '17 at 18:57