Jordi Yu
Jordi Yu

Reputation: 11

Loc return column value instead of index value

I have a df which includes information about the real estate value of some assets and the expected time to sell in months:

df_data = pd.DataFrame({'Asset_Id':[1,2,3]
               ,'REV':[150000.00,200000.00,250000.00]
               ,'TTS':[9,12,15]})

I am trying to translate this information into a cash flow statement, by creating a new zero-filled dataframe and replacing its values with a loc

df_CF = pd.DataFrame({'Income':[0.00 for n in (range(0,24))],
              'Months':range(0,24)})

df_CF.iloc[df_data.TTS,0] = df_data.REV

However, this code is replacing the 'Income' values with the values in the index position of the "Data" table, not the value that matches its TTS with the cash flow dataframe position. Since the "Data" table only contains 3 rows, this is returning an NaN.

In the "CF" dataframe, the expected return should be 150.000 in month 9, 200.000 in month 12, and 250.000 in month 15.

Upvotes: 0

Views: 195

Answers (2)

jezrael
jezrael

Reputation: 862521

I believe need map:

df_CF['Income']=df_CF['Months'].map(df_data.set_index('TTS')['REV']).fillna(df_CF['Months'])
print (df_CF)
      Income  Months
0        0.0       0
1        1.0       1
2        2.0       2
3        3.0       3
4        4.0       4
5        5.0       5
6        6.0       6
7        7.0       7
8        8.0       8
9   150000.0       9
10      10.0      10
11      11.0      11
12  200000.0      12
13      13.0      13
14      14.0      14
15  250000.0      15
16      16.0      16
17      17.0      17
18      18.0      18
19      19.0      19
20      20.0      20
21      21.0      21
22      22.0      22
23      23.0      23

Upvotes: 1

llllllllll
llllllllll

Reputation: 16404

You can use:

df_CF.iloc[df_data.TTS,0] = df_data.REV.values

Upvotes: 0

Related Questions