169 lines
6.7 KiB
Python
169 lines
6.7 KiB
Python
"""
|
|
物业费等级计算
|
|
"""
|
|
from goojia_utils import ElasticSearchClient, nextcloudutils
|
|
import pandas as pd
|
|
import logging
|
|
import os
|
|
import sys
|
|
from elasticsearch import helpers
|
|
import matplotlib.pyplot as plt
|
|
|
|
from sklearn.mixture import GaussianMixture
|
|
from sklearn.preprocessing import QuantileTransformer
|
|
|
|
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"
|
|
|
|
nextcloud_aim_file_path = '共享/财力评级/物业费等级图'
|
|
|
|
save_path_prefix = "/home/airflow/data/community"
|
|
save_png_path = save_path_prefix + "/estate_charge_ranking"
|
|
if not os.path.exists(save_png_path):
|
|
os.makedirs(save_png_path)
|
|
|
|
factor_df = pd.read_excel(path + '/财力评级极值设置.xlsx')
|
|
factor_dict = dict()
|
|
for index, item in factor_df.iterrows():
|
|
if pd.isna(item['min_total_price']):
|
|
continue
|
|
factor_dict[item['city']] = {'min_total_price': item['min_total_price'], 'max_total_price': item['max_total_price'], 'min_estate_charge': item['min_estate_charge'], 'max_estate_charge': item['max_estate_charge'], \
|
|
'min_avg_cost': item['min_avg_cost'], 'max_avg_cost': item['max_avg_cost']}
|
|
|
|
|
|
reasonable_df = pd.read_excel(path + '/财力评级物业费等级情况20221213.xlsx')
|
|
reasonable_dict = reasonable_df.set_index('city')['是否合理'].to_dict()
|
|
|
|
|
|
def gmm_train(total_rate, consumption_df, source, target):
|
|
# 高斯混合模型
|
|
city_info = consumption_df.loc[0, 'city']
|
|
if city_info in reasonable_dict and reasonable_dict[city_info] == '不合理':
|
|
gmm = GaussianMixture(n_components=total_rate, covariance_type='tied', max_iter=200, n_init=10).fit(consumption_df[[source]])
|
|
else:
|
|
gmm = GaussianMixture(n_components=total_rate).fit(consumption_df[[source]])
|
|
consumption_df['cluster'] = gmm.predict(consumption_df[[source]])
|
|
consumption_df['price_mean_cluster'] = consumption_df.groupby('cluster')[source].transform('mean')
|
|
consumption_df[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 filter_min_max(community_summary_df):
|
|
"""
|
|
噪音词处理
|
|
"""
|
|
community_summary_df['QuantileTransformer.normal'] = QuantileTransformer(output_distribution="normal").fit_transform(community_summary_df[['estate_charge']])
|
|
# estate_charge5 = np.percentile(a=community_summary_df['estate_charge'], q=1, axis=0)
|
|
# estate_charge95 = np.percentile(a=community_summary_df['estate_charge'], q=99, axis=0)
|
|
# community_summary_df.loc[community_summary_df['estate_charge'] > estate_charge95, 'estate_charge'] = estate_charge95
|
|
# community_summary_df.loc[community_summary_df['estate_charge'] < estate_charge5, 'estate_charge'] = estate_charge5
|
|
# if city in factor_dict:
|
|
# community_summary_df.loc[
|
|
# community_summary_df['estate_charge'] < factor_dict[city]['min_estate_charge'], 'estate_charge'] = \
|
|
# factor_dict[city]['min_estate_charge']
|
|
# community_summary_df.loc[
|
|
# community_summary_df['estate_charge'] > factor_dict[city]['max_estate_charge'], 'estate_charge'] = \
|
|
# factor_dict[city]['max_estate_charge']
|
|
return community_summary_df
|
|
|
|
|
|
def calc_estate_charge_rating(community_summary_df):
|
|
"""
|
|
计算物业费等级
|
|
"""
|
|
df = community_summary_df[['_id', 'city', 'QuantileTransformer.normal', 'estate_charge']].copy()
|
|
source = "QuantileTransformer.normal"
|
|
target = "estate_charge_ranking"
|
|
actions = list()
|
|
count = 0
|
|
|
|
if len(df) < 5:
|
|
# 对于样本低于5的直接排名
|
|
df[target] = df['estate_charge'].rank(method='dense', ascending=False).astype(int)
|
|
else:
|
|
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))
|
|
return df
|
|
|
|
|
|
def sync_by_city(city_now):
|
|
log.info(f"{city_now}开始评级....")
|
|
sql = "select id, city, region, name, estate_charge from community_summary where city='" + city_now + "'"
|
|
community_summary_df = es206_client.scan_by_sql_to_data_frame(sql)
|
|
columns = community_summary_df.columns
|
|
if 'estate_charge' not in columns:
|
|
log.warning(f"{city_now}无法评级,缺少因子")
|
|
return
|
|
community_summary_df = community_summary_df.dropna(how='any').reset_index(drop=True).copy()
|
|
# 噪音词处理
|
|
community_summary_df = filter_min_max(community_summary_df)
|
|
community_summary_df = calc_estate_charge_rating(community_summary_df)
|
|
if len(community_summary_df) == 0:
|
|
log.warning(f"{city_now}无法评级,数量低于5")
|
|
return
|
|
save_png(community_summary_df)
|
|
nextcloudutils.up_to_nextcloud(save_png_path + "/" + city_now + ".png", nextcloud_aim_file_path + "/" + city_now + ".png")
|
|
|
|
|
|
def sync(city=None):
|
|
if pd.isna(city):
|
|
for city_now in reasonable_df['city'].unique():
|
|
#if reasonable_dict[city_now] == '不合理':
|
|
sync_by_city(city_now)
|
|
else:
|
|
sync_by_city(city)
|
|
|
|
|
|
def save_png(community_city):
|
|
"""
|
|
生成财力评级图表
|
|
"""
|
|
plt.subplot(2, 1, 1)
|
|
community_city['estate_charge_ranking'].hist(bins=100)
|
|
plt.xlabel('estate_charge_ranking')
|
|
plt.tight_layout()
|
|
|
|
plt.subplot(2, 1, 2)
|
|
community_city['estate_charge'].hist(bins=100)
|
|
plt.xlabel('estate_charge')
|
|
plt.tight_layout()
|
|
|
|
plt.savefig(save_png_path + "/" + community_city['city'].unique()[0] + ".png")
|
|
# 清图
|
|
plt.clf()
|
|
# 清坐标轴
|
|
plt.cla()
|
|
# 关窗口
|
|
plt.close()
|
|
|
|
|
|
city = sys.argv[1] if len(sys.argv) > 1 else None
|
|
sync(city)
|
|
#dingutils.send_text("【分布图生成完毕】物业费评级已完成, 请点击 https://nextcloud.fangjia.com/s/HbifLoEDc5wi8HR 查看分布图", "c7ac6c86bfbe49a95e30a68616c4d784ae7781c715430dc9c5f6b46d3e6ebd78") |