0

I got a problem when I try to calculate the mean,my data types is object. enter image description here when im trying this code to get a mean,all i got is NaN value in my kurs_tengah column.

df['kurs_tengah'] = df[['kurs_jual','kurs_beli']].mean()

heres the data enter image description here

what did i do wrong?please tell me! thank you in advance

adinda aulia
  • 183
  • 3
  • 12
  • 1) You can't really do `mean` on object type. 2) the right hand side `df[['kurs_jual','kurs_beli']].mean()` is a series indexed by `'kurs_jual','kurs_beli'` which is most likely different from that of `df`. – Quang Hoang Feb 01 '21 at 04:18
  • thank you,before im trying to convert object to float but i still get the same result.can you give me a solution? – adinda aulia Feb 01 '21 at 04:22
  • Can you provide some data from your `dataframe` in question ? @adindaaulia if your `'kurs_jual'`,`'kurs_beli'` is currently as `object type` (and it actually is numbers) then simply typecast it to number type and then apply mean method. – k33da_the_bug Feb 01 '21 at 04:26
  • okay!please check it out – adinda aulia Feb 01 '21 at 04:27

1 Answers1

0

Since you are getting a series with 2 mean column values, consider assigning to 2 columns like new_col1, new_col2 below. Also convert the right hand side into list, like -

df[['new_col1', 'new_col2']] = df[["kurs_jual", "kurs_beli"]].mean().to_list()
Yogi
  • 38
  • 6
  • thank you but i got this error "None of [Index(['new_col1', 'new_col2'], dtype='object')] are in the [columns]" – adinda aulia Feb 01 '21 at 05:03
  • Can you paste the code you executed that resulted in this error? – Yogi Feb 01 '21 at 05:58
  • df[['new_col1', 'new_col2']] = df[["kurs_jual", "kurs_beli"]].mean().to_list(),i just follow ur instruction..sorry if im wrong – adinda aulia Feb 01 '21 at 06:46
  • @adinda, try this method as below for individual column assignments - df['new_col1'], df['new_col2'] = df[["kurs_jual", "kurs_beli"]].mean().to_list() There are various approaches to handle multiple column assignments from a list, you can find more details here - https://stackoverflow.com/questions/39050539/how-to-add-multiple-columns-to-pandas-dataframe-in-one-assignment – Yogi Feb 01 '21 at 13:23