Reputation: 139
Trying to run this simple for loop with a pandas cross tab function. The iteration target is an argument in the cross-tab function. It's supposed to read through a list of columns and produce a cross-tab for each column combination. But instead it's interpreting my 'i' iterable as the literal title of the column instead of whatever variable it should be in that iteration.
I get the error: 'DataFrame' object has no attribute 'i' because it's reading 'i' as the literal name of an attribute instead of the value that should be stored in i from the loop.
import pandas
DF = pandas.read_excel('example.xlsx')
Categories = list(DF.columns.values)
for i in Categories:
pandas.crosstab(DF.Q, DF.i, normalize = 'index', margins=True)
Upvotes: 1
Views: 64
Reputation: 18647
IIUC, you want to loop though every column and create the cross tab against column Q
, but your current loop won't produce anything.
Use the following to assign the results to a python dict
that you can access with column names as the key:
DF = pandas.read_excel('example.xlsx')
Categories = list(DF.columns.values)
cross_tabs = {}
for i in Categories:
cross_tabs[i] = pandas.crosstab(DF.Q, DF[i], normalize = 'index', margins=True)
Upvotes: 2