Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

python - How to fix AttributeError: 'NoneType' object has no attribute 'loc'(Pandas)?

I have a pandas script.

import pandas as pd

data = pd.read_csv('sample.csv',delimiter=',')

def mapping(df):
     #work of data mapping
     for column_name, column in df.transpose().iterrows():
         df.rename(columns ={'first name' : 'FNAME', 'secret': 'CODE'}, inplace = True)
         df.rename(columns ={'alias' : 'FNAME', 'code': 'CODE'}, inplace = True)
         df.rename(columns ={'initial name' : 'FNAME', 'id': 'CODE'}, inplace = True)

final_df = mapping(data)

#If the code is greater than 12 digits, leave it blank
final_df.loc[final_df['CODE'].astype(str).str.len() >12, 'CODE']= ''

I'm getting the error as :

final_df.loc[final_df['CODE'].astype(str).str.len() >12, 'CODE']= ''
AttributeError: 'NoneType' object has no attribute 'loc'

Any fixes for this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your mapping function does not return anything. So when you assign it to final_df, nothing would be assigned to it making it None.

You should add return df to the last line of your function to get what you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...