我正在遍历管道,以打印出名为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]。
1800 [-8.73800344]
features coefficients
0 1800 -8.738003
hr [-8.73656027]
features coefficients
0 hr -8.73656
wa [-8.7336777]
features coefficients
0 wa -8.733678
1400 [-8.72197545]
features coefficients
0 1400 -8.721975
hrwa [-8.71952656]
features coefficients
0 hrwa -8.719527
perimeter [-8.71173264]
features coefficients
0 perimeter -8.711733
response [-8.67388885]
features coefficients
0 response -8.673889
analysis [-8.65460329]
features coefficients
0 analysis -8.654603
00 [-8.58386785]
features coefficients
0 00 -8.583868
raw [-8.56148006]
features coefficients
0 raw -8.56148
run [-8.51374794]
features coefficients
0 run -8.513748
factor [-8.50725691]
features coefficients
0 factor -8.507257
200 [-8.50334896]
features coefficients
0 200 -8.503349
file [-8.39990841]
features coefficients
0 file -8.399908
pb [-8.38173753]
features coefficients
0 pb -8.381738
mar [-8.21304343]
features coefficients
0 mar -8.213043
1998 [-8.21239836]
features coefficients
0 1998 -8.212398
signal [-8.02426499]
features coefficients
0 signal -8.024265
area [-8.01782987]
features coefficients
0 area -8.01783
98 [-7.3166918]
features coefficients
0 98 -7.316692
我如何像这样返回
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]
我研究了几个类似的问题here,here和here,但是它似乎并不能直接解决我的问题。
预先谢谢您,仍然在这里学习。
最佳答案
我尝试模拟一些数据,您可以在循环的每个步骤中将list
附加到L
,最后从df
创建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)
样品:
import pandas as pd
f = [[1],[2],[3]]
c = ['a','b','c']
L = []
for i in range(3):
# print(f[i],c[i])
#swap c and f
L.append([c[i], f[i][0]])
print (L)
[['a', 1], ['b', 2], ['c', 3]]
df = pd.DataFrame(L, columns = ['features', 'coefficients'])
print(df)
features coefficients
0 a 1
1 b 2
2 c 3
关于python - 防止 Pandas 数据框标题行在for语句中重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38038383/