Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

serier to tolist() gives elements in squared brackets when appended python

When i convert the series object to list and append each element to a new list the elements are added with extra squared brackets.

Can someone help me on how to remove the brackets or append without adding extra bracket for each element

import pandas as pd

df = pd.DataFrame({'col1':[10,20,30],'col2':[40,50,60]})
print(df.head())
df_fd = pd.DataFrame({'variable':['col1','col1','col1','col2','col2','col2'],'Value':[10,20,30,40,50,60],'ratio':[0.1,0.2,0.3,0.4,0.5,0.6]})

print(df_fd)

df_new = pd.DataFrame()
print(df.head())
for col in df.columns:
    ratio_list = []
    print('Columns:',col)
    for val in df[col].unique():
        print('Instance:',val)
        print('Ratio value:',(df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio']))
        ratio = df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio']
        ratio = list(ratio)
        print('ratio:',ratio)
        ratio_list.append(ratio)
        print(ratio_list)
    df_new['ratio'] = ratio_list    
    df_new.rename(columns={"ratio":"Ratio_"+col},inplace=True)
    print(df_new.head())

df = pd.concat([df,df_new],axis=1)
print(df.head())
I get output something like this :
[[0.1], [0.2], [0.3]] 

col1  col2 Ratio_col1 Ratio_col2
0    10    40      [0.1]      [0.4]
1    20    50      [0.2]      [0.5]
2    30    60      [0.3]      [0.6]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

ratio = df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio'].values[0]

remove

  • ratio=list(ratio)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading