I would like to add a new column to the data frame and do the calculation.

Asked 2 years ago, Updated 2 years ago, 80 views

"We would like to add the column ""Assessment"" to the sales data like the image to evaluate ""A, B, C""

"
for index, id in enumerate (data['ID'].unique()):
    sm_data=data[data['ID']==id]

"Create Column"
    sm_data['Assessment'] = 'A'

    result=list(sm_data["Sales"))

    for i in result:
    
    if i<20000:
        sm_data['Assessment'].append('A')
    
    elifi<8000:
        sm_data['Assessment'].append('C')
        
    else: sm_data['Assessment'].append('B')

The error code reads as follows:

TypeError:cannot concatenate object of type'<class'str'>';only Series and DataFrame objs are valid

How can I add an evaluation to the column I added?
Thank you for your cooperation.

Sales data

Sales data

python csv

2022-09-30 15:56

2 Answers

The following is a case of using pandas.Series.map.

import pandas as pd

df = pd.DataFrame({
  'ID': [10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20],
  'name': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B'],
  "Month" : ['January 1, 2017', 'February 1, 2017', 'March 1, 2017', 'April 1, 2017', 'May 1, 2017',
         '2017/1/1', '2017/2/1', '2017/3/1', '2017/4/1', '2017/5/1'],
  Sales: [9786, 8464, 20291, 13130, 33974, 6459, 5586, 13392, 8666, 22423],
}) 

df['Assessment'] = df['Sales'].map(
               lambdax: 'A' if x > 20,000 else ('C' if x <8000 else' B')

pd.set_option('display.unicode.east_asian_width', True)
print(df)

=>
   ID name Monthly Sales Assessment
0 10 A 2017/1/19786 B
110 A 2017/2/18464 B
210 A 2017/3/1 20291 A
310 A 2017/4/1113130 B
410 A 2017/5/133974 A
520 B 1/16459 C of 2017
620 B 2017/2/15586 C
720 B 2017/3/113392 B
820 B 2017/4/18666 B
920B 2017/5/122423A


2022-09-30 15:56

An error occurred because you are calling append() that does not exist in the Series.

To conditionally update the value in the Evaluation column (although there are other options):

sm_data.loc[sm_data["Sales"]<8000, 'Assessment'] = 'C'

Also, the if portion is strange.

if i<20000:
        sm_data['Assessment'].append('A')
    
    elifi<8000:

This is A because any value less than 8000 will be in the first if statement.

Note: The following three lines are sufficient if sales exceed 20,000 yen.

 sm_data['Assessment'] = 'B'
sm_data.loc[sm_data["Sales"]>20000, 'Assessment'] = 'A'
sm_data.loc[sm_data["Sales"]<8000, 'Assessment'] = 'C'


2022-09-30 15:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.