Reputation: 504
I have a dataframe with survey data, where each column is labelled Q1-Q100. The first row in the dataframe contains the actual questions from the survey (one question for each column). I would like to set that row as an attribute or meta data for each column so I can reference it later.
The dataframe looks like this:
Q1 Q2 Q3 Q4
ID Age Gender Handedness
1 19 Female Right
2 19 Male Right
3 25 Female Right
4 17 Female Left
But for Q10-100 the label is a full sentence/question rather than a short label like 'Age'.
I know I can set attributes individually using:
df.attrs['Q1'] = 'This is an example question'
But am looking to see if there is a way to set the entire row as the attributes for each associated column, without having to loop through each column and set them one at a time.
Upvotes: 0
Views: 275
Reputation: 2412
Why can't you use a loop, simply?
If you have the questions stored as a list, you can just do something like:
for column, question in zip(df.columns, questions):
df.attrs[column] = question
PS: If you need to have the questions stored in df
's first row as a list, just do:
questions = df.iloc[0].tolist()
df = df.drop(df.index[0], axis=0)
Upvotes: 1