Restructurer un tableau de données dyadiques

De EduTech Wiki
Aller à la navigation Aller à la recherche

Restructure data table from individual to dyadic structure

This script requires python3+ and pandas library.

Install pandas with pip : python -m pip install –upgrade pandas in command prompt/terminal

Individual structure :

Fichier:Attachment:dyadic individual structure.gif
caption dyadic_individual_structure.gif

Dyadic structure :

Fichier:Attachment:dyadic dyadic structure.gif
caption dyadic_dyadic_structure.gif

Code

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pandas as pd

Specify folder path

os.chdir('D:\\Google Drive\\1-These\\13-EATMINT2\\Analyses\\Questionnaires')

Specify .csv file name

df1 = pd.read_csv('questionnaire_raw_data_individual_structure.csv',sep=';')

Delete columns without data structure change needed

data = df1.drop(['Dyade','Sujet','Sexe','Condition'], axis = 1)

Put columns names in a list

variables = data.columns

Create a new data frame

new_data = pd.DataFrame()

For each column, get even values and put them in p1 (resp. odd values in p2). Give the same index to both p1 and p2. Add both renamed columns in the data frame

for i in variables:
    p1 = data[i].iloc[::2]
    p1.index = range(1,len(p1)+1)
    
    p2 = data[i].iloc[1::2]
    p2.index = range(1,len(p2)+1)

    v = i
    v1 = i + '_p1'
    v2 = i + '_p2'
    
    new_data[v1] = p1
    new_data[v2] = p2

Export restructured data

new_data.to_csv('out.csv',sep=';')