We are committed to safeguarding the privacy of our website visitors, readers, and service users. Any data you send us will be used in a lawful way. We won't do anything with it that we did not tell you about in advance, and it will all remain private unless you give permission to send specific data to a third party for a good reason.
Name and Email Address: When you contact oakwoodbookfest.co.uk, we ask for your name, email address, and other information specific to your question. We keep the information we collect from you to a minimum, just the necessary details to provide services or answer your questions.
It is a priority to maintain the privacy of your personal information and take all appropriate technical and organizational precautions to secure your personal data and to prevent its loss, misuse, or alteration.
Please Note: You acknowledge that the transmission of unencrypted data over the internet is inherently insecure, and We cannot guarantee its security. You should ensure that your password is not susceptible to being guessed, whether by a person or a computer program. You are responsible for keeping the password you use for accessing my website confidential and We will not ask you for your password (except when you log in to the website).
What If Oakwoodbookfest.co.uk Has Wrong Information About You?
Please Note: If you block cookies, you will not be able to use all the features of our website.
Does Oakwoodbookfest.co.uk disclose information to outside parties?
We cannot accept responsibility or liability for the content or activities of linked sites. These individuals or companies have their own independent privacy and cookies policies, which you need to check separately.
The right to data portability: You have the right to object to our processing of your personal data for direct marketing purposes (including profiling for direct marketing purposes). We do not use your data for such, beyond the provision of newsletters and updates about our events and associated authors books. If you make such an objection, We will cease to process your personal data for this purpose.


text:
Q: Restructure dataframe (maybe pivot or unpivot) to have each column display the label of data based on 0's and 1's I have survey data. The survey asks a question and the respondents pick one or more given categories for each question. The survey then asks demographic questions such as gender. The output is a dataframe with demographic information as columns and a matrix of 0's and 1's for each category in each question (0 = not selected and 1 = selected).
To help you better understand how this looks like I have the following data frame:
df = pd.DataFrame({'Survey ID': [1,2,3],
                   'Q1_Topic A': [0,1,1],
                   'Q1_Topic B': [1,0,1],
                   'Q1_Topic C': [1,0,0],
                   'Q2_Topic X': [0,0,1],
                   'Q2_Topic Y': [0,1,0],
                   'Q2_Topic Z': [0,0,1],
                   'Gender': ['Male', 'Female', 'Male']
                  })
print(df)

I need to transform this dataframe to show me a column for each question and multiple rows for each survey depending on how many categories were chosen. Each row should have a category under the relevant question column.
Confused yet? Its hard to explain but the data should look like
df2 = pd.DataFrame({'Survey ID': [1,1,2,3,3],
                   'Q1': ['B','C','A','A','B'],
                   'Q2': [float('nan'), float('nan'), 'Y', 'X', 'Z'],
                   'Gender': ['Male', 'Male', 'Female', 'Male', 'Male']
                    })
print(df2)

Basically I need to transform df to df2.
Note: There is a common separator of "_" for the question and topic for each column label.
As always thanks a lot for you help in advanced. Without this community I would be seriously stuck sometimes and I am learning a lot through this platform.

A: Use:
#convert to MultiIndex all not Q topic columns
df2 = df.set_index(['Survey ID','Gender'])
#split columns names to MultiIndex in columns
df2.columns = df2.columns.str.split(expand=True)
#reshape
df2 = df2.stack()
#filter only rows with at least one 1 per row and reshape for remove NaNs
#also replace 0 to NaNs
df2 = df2[df2.eq(1).any(axis=1)].replace(0, np.nan).stack().reset_index(level=2)

#added helper level to MultiIndex because possible duplicates by counter
df2['g'] = df2.groupby(level=[0,1,2]).cumcount()
#final reshape
df2 = (df2.set_index('g', append=True)['level_2']
          .unstack(2)
          .reset_index(level=2, drop=True)
          .reset_index())

print (df2)
   Survey ID  Gender Q1_Topic Q2_Topic
0          1    Male        B      NaN
1          1    Male        C      NaN
2          2  Female        A        Y
3          3    Male        A        X
4          3    Male        B        Z

A: How about this code? It is not fancy code, but intuitive.
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'Survey ID': [1,2,3],
                   'Q1_Topic A': [0,1,1],
                   'Q1_Topic B': [1,0,1],
                   'Q1_Topic C': [1,0,0],
                   'Q2_Topic A': [0,0,1],
                   'Q2_Topic B': [0,1,0],
                   'Q2_Topic C': [0,0,1],
                   'Gender': ['Male', 'Female', 'Male']
                  })

values = []

for ind, row in df1.iterrows():
    survey_ID = row['Survey ID']
    Gender = row['Gender']
    Q1 = row['Q1_Topic A'] * ['A'] + row['Q1_Topic B'] * ['B'] + row['Q1_Topic C'] * ['C']
    Q2 = row['Q2_Topic A'] * ['A'] + row['Q2_Topic B'] * ['B'] + row['Q2_Topic C'] * ['C']

    for i in range(max(len(Q1), len(Q2))):
        if i >= len(Q1):
            record = [survey_ID, np.nan, Q2[i], Gender]
        elif i >= len(Q2):
            record = [survey_ID, Q1[i], np.nan, Gender]
        else:
            record = [survey_ID, Q1[i], Q2[i], Gender]
        values.append(record)

df2 = pd.DataFrame(values, columns = ['Survey ID', 'Q1', 'Q2', 'Gender'])

redpajama_set_name: RedPajamaStackExchange


Mancos High School was built in 1909, and the entire community prides itself on having the longest continuously used high school in the State of Colorado. Small class sizes provide for an intimate classroom teaching environment where teachers can develop strong, positive relationships one-on-one with their students. Our teachers provide 21st Century learning experiences which focus on feedback from the students and completion of significant projects which help students showcase the skills learned in classes.
The location of Mancos High School allows us to offer concurrent enrollment opportunities for upper-classmen where students can take courses offered either at Southwest Colorado Community College near Cortez, Colorado, as well as Fort Lewis College in Durango, Colorado. Both are within a 30-mile radius.
Mancos High School offers competitive sports and academic programs in Volleyball, Football, Cross Country, Basketball, Track, Science Fair, and Knowledge Bowl where many of our students have successfully competed at the state level. We are proud of our students and collectively strive to prepare them in the best ways possible for what is to come after high school.


Happy Holiday greetings to you from The Mountain!
We are reaching out to you to ask for your financial support again this year. We are making good progress toward our ambitious Annual Funding goal of $260,000, but we aren't quite there. SO, each and every gift of any size brings us closer to achieving that goal possible. Please make your gift to the Annual Fund before the end of the year.
Here's why your support matters: The Mountain has been enriching the lives of thousands of people for four decades–creating a strong and supportive community and caring for our precious natural setting. The Mountain will not thrive and grow in the future without your participation and support to sustain it along the way.
We welcomed over 3,000 guests, including 260 Campers, 60 groups and congregation retreats, 6 Youth CONferences, and dozens of personal retreats.
We are grateful for our 300+ donors who gave over $400,000 for annual and special project funding in 2017.
Our Many Hands Peace Farm is flourishing, producing food and eggs for our guests and selling at local markets, hosting farm tours for all ages, creating a Food Forest, and offering a new Farm Camp week in 2019.
Many facility improvements have been made to enhance the guest experience and conserve on energy–new energy efficient windows, cabin and meeting room renovations, resurfacing Ring Road, door opening systems, railings, and more.
Hundreds of children and youth participate in our six weeks of MountainCam ps and seven Youth CONference weekends each year. For our young guests, camp counselors, and youth advisors, these are experiences they treasure and will never forget.
Our Mountain Campership Fund provides camperships for 40 kids to experience MountainCamp who may not otherwise be able to participate. We believe every kid deserves a MountainCamp experience!
The Mountain is all about its mission, which is what your annual contributions go directly to support. Contributions to the annual fund make up about 25% of the operating budget, enabling us to keep our camp, program, and retreat costs reasonable for all our guests. The Mountain staff works hard throughout the year to make the most of every dollar received.
We cannot even imagine the world without The Mountain–the magical place where people of all ages share life-enriching experiences and make lasting memories. Your Annual Membership and gifts to The Mountain and Mountain Campership Fund make it all possible.
Thank You from all of us at The Mountain!
Click HERE for our Holiday Greetings video.