|
| 1 | +importpandasaspd |
| 2 | + |
| 3 | +# Config settings |
| 4 | +pd.set_option('max_columns',None) |
| 5 | +pd.set_option('max_rows',12) |
| 6 | + |
| 7 | +# Import CSV data |
| 8 | +data_frames=pd.read_csv (r'simulated_data.csv') |
| 9 | + |
| 10 | +# Data Type Conversion |
| 11 | +# Remove '$' from donation strings |
| 12 | +data_frames['donation']=data_frames['donation'].str.strip('$') |
| 13 | + |
| 14 | +# Convert donation stings into numerical data type |
| 15 | +data_frames['donation']=data_frames['donation'].astype('float64') |
| 16 | + |
| 17 | + |
| 18 | +# Handle Data Inconsistencies |
| 19 | +# Normalize strings |
| 20 | +data_frames['street_address']=data_frames['street_address'].str.split() |
| 21 | + |
| 22 | +defnormalize_words(arr): |
| 23 | +forindex,wordinenumerate(arr): |
| 24 | +ifindex==0: |
| 25 | +pass |
| 26 | +else: |
| 27 | +arr[index]=normalize(word) |
| 28 | + |
| 29 | +defnormalize(word): |
| 30 | +ifword.lower()=='st': |
| 31 | +word='street' |
| 32 | +elifword.lower()=='rd': |
| 33 | +word='road' |
| 34 | + |
| 35 | +returnword.capitalize() |
| 36 | + |
| 37 | + |
| 38 | +data_frames['street_address'].apply(lambdax:normalize_words(x)) |
| 39 | +data_frames['street_address']=data_frames['street_address'].str.join(' ') |
| 40 | + |
| 41 | + |
| 42 | +# Remove Out-of-Range Data |
| 43 | +# create boolean Series for out of range donations |
| 44 | +out_of_range=data_frames['donation']<0 |
| 45 | + |
| 46 | +# keep only the rows that are NOT out of range |
| 47 | +data_frames['donation']=data_frames['donation'][~out_of_range] |
| 48 | + |
| 49 | + |
| 50 | +# Remove duplicates |
| 51 | +columns_to_check= ['first_name','last_name','street_address','city','state'] |
| 52 | +data_frames_no_dupes=data_frames.drop_duplicates(subset=columns_to_check,keep='first') |
| 53 | + |
| 54 | + |
| 55 | +# Drop Missing Data |
| 56 | +columns_to_check= ['state','donation'] |
| 57 | +data_frames_no_missing=data_frames_no_dupes.dropna(subset=columns_to_check) |
| 58 | + |
| 59 | + |
| 60 | +print(data_frames_no_missing.head(20)) |