Storing data in a data frame

New to python. I am struggling for a way to combine an operation on my raw data and a way to store it in a dataframe and then use it again with pandas and R.

some example of my code:

if 'Subject' in f:
     for i in range (len(time)):
          (...)
                    if  Description[j] == 'response':  
                        RT.append(time[j] - time_stim)
                        motor_time.append(time[j] - time_response)                
                        break

      

My raw data is an example .txt file below:

Type,Description,Time,Channel 
Categorie,PC,153,1,All 
Stimulus,S11,1510,1,All 
Stimulus,S202,3175,1,All 
Stimulus,EMG_Onset,3978,1,EMGL 
Stimulus,response,4226,1,All 
Categorie,CC,5785,1,All 
Stimulus,S11,7141,1,All 
Stimulus,S202,8807,1,All 
Stimulus,EMG_Onset,9549,1,EMGL
Stimulus,EMG_Onset,9965,1,EMGL 
Stimulus,response,10249,1,All

      

In this example, I want to store the RT or motor_time that I got from this piece of code in a still non-existent dataframe, so I can use it first with python and then with R. This dataframe would have to store all parameters for all my experimental conditions and thing

In this case, all the results are stored in a numeric np.array and I don't know how to use them with the specific R code I created earlier.

Thank.

+3


source to share


2 answers


I finally found an easy way, I probably didn't know what to look for and how to ask, but here's my solution:

df_trans = pd.DataFrame({'Sujet': np.array(subj_id),
                   'Temps_moteur': np.array(motor_time),
                   'TR' : np.array(RT),
                   ...})

      

and keep it and use it in R:



df_trans.to_csv('x.csv')

      

Thanks Pandas!

0


source


I must first say that I see no reason to mix python and R.

If you already have analysis in R, you can directly read your TXT file in R dataframe

df = read.csv("myfile.txt")
head(df)  # to display the first few rows of your data frame

      

Your 1, 2, and 5 columns will be converted to factors (you can change them if you like).

If you want to use python you can read your file into pandas DataFrame.



import pandas as pd
df = pd.read_csv("myfile.txt")
df.head()  # to display the first few rows of your data frame

      

If this is not a solution to your question, please indicate what you want outside of this?

There is an rpy package that allows you to use R code in python. This requires additional python programming code anyway.

As for importing a pandas dataframe into R: I would save it as a CSV file or some other format (save as "save to hard drive") and then open it in R. But the CSV file is what you initially get, so you not necessary.

+1


source







All Articles