简体   繁体   中英

Removing brackets from SQL connexion in Python dataframe

I'm new here

I have a table out of a SQL query in my Python Notebook which gives me the following dataframe:

在此处输入图片说明

My ultimate goal is to group by the second column, which is a boolean, and get the mean per group of the first column (ranges from 1 to 10)

The problem is I haven't been able to remove the brackets efficiently, thus making it impossible to calculate anything from the 1st column. So far I have tried this:

val = df.values
val

Followed by:

list = [i[0] for i in val]
z = map(ast.literal_eval,list)
zz= list(z)
zz

which had worked went I wanted to use a value such as: [ 367, 368, 370] from a column (which are choices from a multiple choice question, to give you a bit of context) But in this case it doesn't work. Maybe because of the Boolean next to it ? I really don't know.

EDIT: SQL Query:

pd.read_sql
('
SELECT U.iUserSexeType, CA.jAnswer 
FROM [User] U 
JOIN DBO.ConsultationAnswer CA ON CA.fkiUserId=U.id 
LEFT JOIN UserAdresse UA ON UA.fkiUserId=U.id 
WHERE fkiConsultationSurveyId=37 and fkiConsultationQuestionId=260
')

Any suggestions ?

You can do this to remove bracket in your sql query:

Select replace(replace(JAnswer,'['),']')
from your table

Your query:

SELECT U.iUserSexeType, replace(replace(CA.jAnswer,'['),']') as jAnswer
FROM [User] U 
JOIN DBO.ConsultationAnswer CA ON CA.fkiUserId=U.id 
LEFT JOIN UserAdresse UA ON UA.fkiUserId=U.id 
where fkiConsultationSurveyId=37 
and fkiConsultationQuestionId=260
    df['value'] = df['value'].str[0]

Or:

    df['value'] = df['value'].str.get(0)

https://stackoverflow.com/a/38147471/7853322

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM