tolist() 的系列在附加 python 时给出方括号中的元素

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

当我将系列对象转换为列表并将每个元素附加到新列表时,添加的元素带有额外的方括号。

有人可以帮助我如何删除括号或附加而不为每个元素添加额外的括号

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

移除

  • 比率=列表(比率)