Home > Enterprise >  python changing value in Dataframe without creating a new in an operation
python changing value in Dataframe without creating a new in an operation

Time:08-11

here are snippets of my codes

sol = []
df = pd.DataFrame({
    'Emp' : ['A1', 'AA12', 'AA132', 'BBB142', 'BB152', 'B132','A221', 'AAA652', 'AA4542', 'BBB1233', 'BB121', 'B1213'],
    'val' : [4560.0, 64.0, 456.0, 34.0, 534.0, 54.0,4560.0, 64.0, 456.0, 34.0, 534.0, 54.0]
}).set_index('Emp')
df2 = pd.DataFrame([2,3,2,3,4,5,6,7,8,5,7,12],columns=['vv'])
for x in range(10):
    sol.append(df.mul(df2.values)['val'].to_list())

what I want to do is change the value of df['B1213'] to 1111 in the code sol.append(df.mul(df2.values)['val'].to_list()) without creating a new dataframe

I tried to convert df to dictionary and use update() function to change the value and change it back to a df. Didnt work and looked quite convoluted. Is there an easier way to do it?

CodePudding user response:

df.loc['B1213'] = 1111

Also, .to_numpy() is the recommended alternative to .values:

Other than that, here is how to write your code shorter:

sol = [(df * df2.to_numpy())['val'].to_list()] * 10

CodePudding user response:

If you don't want to create a copy, just modify the original DataFrame.

for x in range(10):
    df.loc['B1213', 'val'] = 1111
    sol.append(df.mul(df2.values)['val'].to_list())

If you don't want to modify the original you need a copy, even a temporary one. You can use method chaining even if this is a bit cumbersome in this particular case in my opinion:

df.assign(val=df['val'].mask(df.index=='B1213', 1111)).mul(df2.values)['val'].to_list()
  • Related