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]
CodePudding user response:
ratio = df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio'].values[0]
remove
- ratio=list(ratio)