2

My code looks like:

d = pd.read_csv('Collector Output.csv')
df = pd.DataFrame(data=d)
dfa = df.copy()
dfa =  dfa.rename(columns={'OBJECTID': 'Object ID', 'test_no': 'TEST #', 'retest_no': 'RETEST #',
                        'tester': 'TESTED BY', 'date': 'DATE', 'proj_no': 'Project Number',
                        'test_elev': 'TEST ELEVATION', 'curve_no': 'CURVE #', 'curve':
                        'Curve Description', 'dry': 'Dry Maximum Density (pcf)', 'opt': 'OPT. M.C.',
                        'Material Type': 'Material Type', 'AC Thickness': 'AC Thickness', 'AB Thickness': 'AB Thickness',
                        'Wet In-place Density, pcf)': 'Wet In-place Density (pcf)', 'inplace_mo': 'FIELD M.C.',
                        'comp_dryde': 'DRY DENSITY', 'relative_c': 'R.C.', 'addl_notes': 'NOTES',
                        'material_t': 'Material Type', 'wet_inpac': 'Wet In-place', 'comp_dryde': 'comp_dryde', 'relative_c': 'relative compaction',
                        'GlobalID': 'GlobalID', 'GlobalID_2': 'GlobalID 2', 'x': 'EAST', 'y': 'NORTH'})


writer = pd.ExcelWriter('Test Test.xlsx', engine= 'xlsxwriter')
dfa.to_excel(writer, sheet_name='Output')
writer.save()

#Slice the dataframe to get the desired columns by their 'name'
dfb = dfa[['TEST #', 'DATE', 'TESTED BY', 'NORTH', 'EAST', 'TEST ELEVATION', 'CURVE #', 'OPT. M.C.', 'FIELD M.C.', 
          'DRY DENSITY', 'R.C.', 'RETEST #', 'NOTES']] 

When I run it, I get a KeyError that reads ['DRY DENSITY' 'R.C.'] not index. I varified that the names are correct for the columns in the .csv. Why are these two columns giving an issue?

geojasm
  • 121
  • 9
  • In my opinion in original df are not `'comp_dryde'` and `'relative_c'` columns, so rename is not possible. – jezrael May 08 '18 at 18:34

1 Answers1

2

I think need double [[]]:

cols = ['TEST #', 'DATE', 'TESTED BY', 'NORTH', 'EAST', 'TEST ELEVATION', 'CURVE #', 'OPT. M.C.', 'FIELD M.C.', 'DRY DENSITY', 'R.C.', 'RETEST #', 'NOTES']
dfb = dfa[cols]

If some columns are mising add intersection:

dfb = dfa[dfa.columns.intersection(cols)] 
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252