0

I have created a new column, by adding values from one column, to the index of the column from which I have created this new column. However, my problem is the code works fine when I implement on sample column, but when I pass the already existing dataframe, it throws the error, "can only perform ops with scalar values". As per what I found is the code expects dist and that is why it is throwing error.

I tried converting the dataframe to dictionary or to a list, but no luck.

 df = pd.DataFrame({'Name': ['Sam', 'Andrea', 'Alex', 'Robin', 'Kia',    'Sia'], 'Age':[14,25,55,8,21,43], 'd_id_max':[2,1,1,2,0,0]})`

df['Expected_new_col'] = df.loc[df.index + df['d_id_max'].to_list, 'Age'].to_numpy()

print(df)

error: can only perform ops with scalar values.

This is the dataframe I want to implement this code:

      Weight   Name     Age     1     2   abs_max d_id_max
  0     45     Sam      14     11.0  41.0   41.0    2
  1     88     Andrea   25     30.0 -17.0   30.0    1
  2     56     Alex     55    -47.0 -34.0   47.0    1
  3     15     Robin    8      13.0  35.0   35.0    2
  4     71     Kia      21     22.0  24.0   24.0    2
  5     44     Sia      43     2.0   22.0   22.0    2
  6     54     Ryan     45     20.0  0.0    20.0    1
1
  • 1
    Explain what you want to do in a logical matter, instead of "why is my code not working". It's a good idea to also include your expected output based on the dataframe you provided Commented Nov 8, 2019 at 13:33

2 Answers 2

1

Writing your new column like this will not return an error:

df.loc[df.index + df['d_id_max'], 'Age'].to_numpy() 

EDIT: You should first format d_id_max as int (or float):

df['d_id_max'] = df['d_id_max'].astype(int)
Sign up to request clarification or add additional context in comments.

7 Comments

I've updated the answer with something that should work, @Saurabh
@Saurabh I just tried it with the code you posted above, and it worked. Are you trying it out on different code?
Yeah, that's my problem. If you go through my 1st question post, I mentioned that my code does not work the same way when I am passing another existing dataframe.
If you want us to help you, please post an example in which the error reproduces - else there's not much we can do
Can you put something we can copy and paste rather than a screenshot?
|
0

The solution was very simple, I was getting the error because the data type of the column d_id_max was object type, which should be either float or integer, so i change the data type and it worked fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.