1
$\begingroup$

I have data on mchip, chip schip and mcaid that contains the following columns/features: year (between 2000 and 2016), state, age and month. I have a problem with several years. For example, I want to replace the numbers in 2003 (Jan, Feb, March) with numbers from 2002. I used this code:

states = df.state.unique()
for i in range(1, 4):
 for j in range(0, 20):
     for state in states:
         print('0')
         df.loc[(df['year']==2003) & (df['month']==i) & (df['age']==j)& (df['state']==state),'mchip'] = df.loc[(df['year']==2002) & (df['month']==i) & (df['age']==j) & (df['state']==state),'mchip']
         df.loc[(df['year']==2002) & (df['month']==i) & (df['age']==j)& (df['state']==state),'chip'] = df.loc[(df['year']==2002) & (df['month']==i) & (df['age']==j)& (df['state']==state),'chip']
         df.loc[(df['year']==2002) & (df['month']==i) & (df['age']==j)& (df['state']==state),'mcaid'] = df.loc[(df['year']==2002) & (df['month']==i) & (df['age']==j)& (df['state']==state),'mcaid']
         df.loc[(df['year']==2002) & (df['month']==i) & (df['age']==j)& (df['state']==state),'schip'] = df.loc[(df['year']==2002) & (df['month']==i) & (df['age']==j)& (df['state']==state),'schip']

The dataset is large and at the moment there is no way to validate whether the above churns out my desired output. I printed out the tails for 2002 and 2003 after running this code and they are different. Is there a way to do this? Thank you

enter image description here

I have data that looks like this. I want to replace values in 2003 with values in 2002. I had a mistake in the code, I already changed 2002 with 2003. After I ran this code values in 2003 are replaced with Nan. I printed out df.loc[(df['year']==2002) & (df['month']==i) & (df['age']==j) & (df['state']==state),'mchip'] and it returns an object instead of a value, this has to be the reason why values in 2003 are replaced with Nan. Is there a way to get a value from the pandas' data frame instead of an object? Thank you.

$\endgroup$
  • 3
    $\begingroup$ Hi Konstantin, is there a chance you can clarify the question (show us expected output) and the context of this problem so we can all best help? $\endgroup$ – shepan6 Jul 8 at 11:53
  • $\begingroup$ The left side of the assignment only has 2003 in the first line. So you only get the desired output for 'mchip'. $\endgroup$ – oW_ Jul 8 at 23:17
  • $\begingroup$ I figured it out. I used .values[0] to access the value of the specific observation. Thank you. $\endgroup$ – Konstantine Jalaghonia Jul 9 at 18:03

Browse other questions tagged or ask your own question.