[英]How to extract values from a list in Python and put into a dataframe
我训练了一个模型并要求模型产生系数:
modelcoeffs = model.fit(X_train, y_train).coef_
coeffslist = list(modelcoeffs)
例如,这让我很满意:
print(coeffslist):
[0.17005542 0.72965947 0.6833308 0.02509676]
我试图将这 4 个系数分开,但它们似乎不是单个元素?
有谁知道如何将这些分成四个数字?
我试图得到:
df['1'] = coeffslist[0]
df['2'] = coeffslist[1]
df['3'] = coeffslist[2]
df['4'] = coeffslist[3]
但它在df
给了我NaN
。 有没有人有任何想法? 谢谢!
更新
我基本上是想让 coeffs 附加到df
print(df)
1 2 3 4
.... ..... ..... .....
0.17005542 0.72965947 0.6833308 0.02509676
这个coeffslist
看起来不像一个有效的 Python 结构,它缺少逗号。
但你可以试试这个:
import pandas as pd
df = pd.DataFrame([0.17005542, 0.72965947, 0.6833308, 0.02509676])
print(df)
输出:
0
0 0.170055
1 0.729659
2 0.683331
3 0.025097
要将 coefs 作为行,请尝试以下操作:
import pandas as pd
df = pd.DataFrame(columns=list("1234"))
df.loc[len(df)] = [0.17005542, 0.72965947, 0.6833308, 0.02509676]
print(df)
输出:
1 2 3 4
0 0.170055 0.729659 0.683331 0.025097
如果您想添加另一行(追加)coefs,只需执行以下操作:
df.loc[1] = [0.17005542, 0.72965947, 0.6833308, 0.02509676]
print(df)
输出:
1 2 3 4
0 0.170055 0.729659 0.683331 0.025097
1 0.170055 0.729659 0.683331 0.025097
您可以将 [0.17005542 0.72965947 0.6833308 0.02509676] 转换为字符串,在空间上将其拆分,再次转换为浮动,然后附加到数据帧。
str_list= str(coeffslist[0])
float_list= [float(x) for x in str_list.split()]
df=pd.DataFrame(columns=['1','2','3','4'])
a_series = pd.Series(float_list, index = df.columns)
df = df.append(a_series, ignore_index=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.