防止pandas数据帧头行在statement中重复

2024-09-30 04:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在管道中迭代以打印出一个名为safety的类的20个最有用的特性。

classnum_saf = 3
inds = np.argsort(clf_3.named_steps['clf'].coef_[classnum_saf, :])[-20:]
for i in inds: 
   f = feature_names[i]
   c = clf_3.named_steps['clf'].coef_[classnum_saf, [i]]
   print(f,c)
   output = {'features':f, 'coefficients':c}
   df = pd.DataFrame(output, columns = ['features', 'coefficients'])
   print(df)

我想要一个只输出一个头的数据帧,但是我返回这个输出,这个输出看起来像是一次又一次地重复这个头,因为它遍历[I]。

^{pr2}$

如何返回data frame类似于:

          features     coefficients
   0      1800          -8.738003
   ..     ...           ...
   18     area          -8.01783
   19     98            -7.316692

现在,当我返回print(d,f)时,它显示以下最上面的值:

   1800 [-8.73800344]
   hr [-8.73656027]
   wa [-8.7336777]
   1400 [-8.72197545]
   hrwa [-8.71952656]
   perimeter [-8.71173264]
   response [-8.67388885]
   analysis [-8.65460329]
   00 [-8.58386785]
   raw [-8.56148006]
   run [-8.51374794]
   factor [-8.50725691]
   200 [-8.50334896]
   file [-8.39990841]
   pb [-8.38173753]
   mar [-8.21304343]
   1998 [-8.21239836]
   signal [-8.02426499]
   area [-8.01782987]
   98 [-7.3166918]

我研究了一些类似的问题herehere,和here,但它似乎没有直接解决我的问题。

提前谢谢,还在这里学习。


Tags: dfoutputhere管道areastepsnamedfeatures
1条回答
网友
1楼 · 发布于 2024-09-30 04:30:18

我尝试模拟一些数据,您可以在循环的每个步骤中将list附加到L,最后从L创建{}:

L = []
classnum_saf = 3
inds = np.argsort(clf_3.named_steps['clf'].coef_[classnum_saf, :])[-20:]
for i in inds: 
   f = feature_names[i]
   c = clf_3.named_steps['clf'].coef_[classnum_saf, [i]]
   print(f,c)
   #add [0] for removing list of list (it works nice if len of f[i] == 1)
   L.append([c[i], f[i][0]])

df = pd.DataFrame(L, columns = ['features', 'coefficients'])
print(df) 

样品:

^{pr2}$

相关问题 更多 >

    热门问题