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?

1
  • In my opinion in original df are not 'comp_dryde' and 'relative_c' columns, so rename is not possible. Commented May 8, 2018 at 18:34

1 Answer 1

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)] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.