我们如何在Django上表示pandas.series值?

2024-06-25 23:29:26 发布

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

我有以下代码,其中我将熊猫数据帧放入给定数量的容器中:

def contibin(data, target, bins=10):
  #Empty Dataframe
  newDF,woeDF = pd.DataFrame(), pd.DataFrame()
    
  #Extract Column Names
  cols = data.columns
  for ivars in cols[~cols.isin([target])]:
        if (data[ivars].dtype.kind in 'bifc') and (len(np.unique(data[ivars]))>10):
            binned_x = pd.qcut(data[ivars], bins,  duplicates='drop')
            d0 = pd.DataFrame({'x': binned_x, 'y': data[target]})
            #print(d0)
        else:
            d0 = pd.DataFrame({'x': data[ivars], 'y': data[target]})
        d = d0.groupby("x", as_index=False).agg({"y": ["count", "sum"]})
        d.columns = ['Range', 'Total', 'No. of Good']
        d['No. of Bad'] = d['Total'] - d['No. of Good']
        d['Dist. of Good'] = np.maximum(d['No. of Good'], 0.5) / d['No. of Good'].sum()
        d['Dist. of Bad'] = np.maximum(d['No. of Bad'], 0.5) / d['No. of Bad'].sum()
        d['WoE'] = np.log(d['Dist. of Good']/d['Dist. of Bad'])
        d['IV'] = d['WoE'] * (d['Dist. of Good'] - d['Dist. of Bad'])
        #temp =pd.DataFrame({"Variable" : [ivars], "IV" : [d['IV'].sum()]}, columns = ["Variable", "IV"])
        #newDF=pd.concat([newDF,temp], axis=0)
        woeDF=pd.concat([woeDF,d], axis=0)
  return woeDF

我面临的问题是,当我尝试使用Django在前端集成代码时,我无法以我正常看到的方式在Django中表示woeDF['Range']。我试着把熊猫系列转换成字符串,但它仍然不能满足我的需要。为了说明我希望在前端看到的内容,我附加了一张示例表的图片,该示例表是我在客户机建模数据集上运行此代码得到的


Tags: ofnotargetdataframedatadistnppd
1条回答
网友
1楼 · 发布于 2024-06-25 23:29:26

可以使用Dataframe.itertuples(index=False)在对象数组中转换数据帧

然后,您将能够通过名称访问列,从而在Jinja中迭代数据帧。请参见Python中的以下示例:

import pandas as pd

columns = {"name": ["john", "skip", "abu", "harry", "ben"],
           "age": [10, 20, 30, 40, 50]}

df = pd.DataFrame(columns)
print(df)


df_objects = df.itertuples(index=False)
for person in df_objects:
    print("{0}: {1}".format(person.name, person.age))

相关问题 更多 >