80 lines
2.8 KiB
Python
80 lines
2.8 KiB
Python
"""
|
|
物业费等级计算
|
|
"""
|
|
from goojia_utils import ElasticSearchClient
|
|
import pandas as pd
|
|
import numpy as np
|
|
import logging
|
|
from elasticsearch import helpers
|
|
|
|
from sklearn.mixture import GaussianMixture
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
es206_client = ElasticSearchClient(host='192.168.0.206')
|
|
index_name = "community_summary"
|
|
path = "/opt/airflow/dags/repo/dags/business/business/community/data"
|
|
|
|
|
|
|
|
def gmm_train(total_rate, consumption_df, source, target):
|
|
# 高斯混合模型
|
|
gmm = GaussianMixture(n_components=total_rate).fit(consumption_df[[source]])
|
|
consumption_df.loc[:, 'cluster'] = gmm.predict(consumption_df[[source]])
|
|
consumption_df.loc[:, 'price_mean_cluster'] = consumption_df.groupby('cluster')[source].transform('mean')
|
|
consumption_df.loc[:, target] = consumption_df['price_mean_cluster'].rank(method='dense', ascending=False).astype(int)
|
|
consumption_df = consumption_df.drop(columns=['cluster', 'price_mean_cluster'], axis=1)
|
|
return consumption_df
|
|
|
|
|
|
def calc_estate_charge_rating(community_summary_df):
|
|
"""
|
|
计算物业费等级
|
|
"""
|
|
consumption_aim_df = community_summary_df[['_id', 'city', 'estate_charge']]
|
|
consumption_aim_df = consumption_aim_df.dropna(subset=['estate_charge'])
|
|
cities = consumption_aim_df['city'].unique()
|
|
source = "estate_charge"
|
|
target = "estate_charge_ranking"
|
|
actions = list()
|
|
count = 0
|
|
|
|
for city in cities:
|
|
df = consumption_aim_df[consumption_aim_df['city'] == city].copy()
|
|
if len(df) < 5:
|
|
continue
|
|
df = gmm_train(5, df, source, target)
|
|
# 批量更新
|
|
for index, item in df.iterrows():
|
|
row = dict()
|
|
_id = str(item["_id"])
|
|
row['estate_charge_ranking'] = item['estate_charge_ranking']
|
|
|
|
action = {'_op_type': 'update', # 操作 index update create delete
|
|
'_index': index_name, # index
|
|
'_id': _id, # 请勿忘记ID
|
|
'doc': row,
|
|
"_retry_on_conflict": 5
|
|
}
|
|
actions.append(action)
|
|
if len(actions) == 5000:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("评级中: 当前已评级{}".format(count))
|
|
if len(actions) > 0:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("评级完成,共更新: {}".format(count))
|
|
|
|
|
|
def sync(city=None):
|
|
sql = "select id, city, region, name, estate_charge from community_summary"
|
|
if pd.notna(city):
|
|
sql += " where city='" + city + "'"
|
|
community_summary_df = es206_client.scan_by_sql_to_data_frame(sql)
|
|
calc_estate_charge_rating(community_summary_df)
|
|
|
|
sync()
|