130 lines
6.0 KiB
Python
130 lines
6.0 KiB
Python
"""
|
|
百分位计算 1 最好 100最差
|
|
"""
|
|
from goojia_utils import ElasticSearchClient
|
|
import pandas as pd
|
|
import logging
|
|
from elasticsearch import helpers
|
|
import sys
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
|
index_name = "community_summary"
|
|
|
|
|
|
def calc_percentile(city=None):
|
|
"""
|
|
计算消费等级
|
|
"""
|
|
sql = "select id, city, region, name, avg_price, total_price, avg_cost, rent_price, relative_price_ranking, finish_building_date, estate_charge, estate_charge_fix, household_count, build_area from community_summary"
|
|
if pd.notna(city):
|
|
sql += " where city='" + city + "'"
|
|
community_summary_df = es206_client.scan_by_sql_to_data_frame(sql)
|
|
if 'estate_charge_fix' not in community_summary_df.columns:
|
|
community_summary_df['estate_charge_fix'] = 0
|
|
community_summary_df['estate_charge_fix'] = community_summary_df['estate_charge'].combine_first(community_summary_df['estate_charge_fix'])
|
|
community_summary_df['relative_price_ranking'] = community_summary_df['relative_price_ranking'] * 100
|
|
if 'rent_price' not in community_summary_df.columns:
|
|
community_summary_df['rent_price'] = 0
|
|
consumption_aim_df = community_summary_df[['id', 'city', 'avg_price', 'total_price', 'avg_cost', 'rent_price', 'relative_price_ranking', 'finish_building_date',
|
|
'estate_charge_fix', 'household_count', 'build_area']]
|
|
number = []
|
|
for i in range(1, 101):
|
|
number.append(i / 100)
|
|
|
|
percents_actions = list()
|
|
# 计算百分位的字段
|
|
columns = ['avg_price', 'total_price', 'avg_cost', 'rent_price', 'relative_price_ranking', 'finish_building_date',
|
|
'estate_charge_fix', 'household_count', 'build_area']
|
|
for city_now, item in consumption_aim_df.groupby(by=['city']).describe(percentiles=number).iterrows():
|
|
for column in columns:
|
|
for i in range(1, 101):
|
|
if str(i) + '%' in item[column]:
|
|
if pd.notna((item[column])[str(i) + '%']):
|
|
action = {'city': city_now, 'type': column,
|
|
'price': int((item[column])[str(i) + '%']), 'percent': i}
|
|
else:
|
|
if pd.notna((item[column])[str(i) + '.0%']):
|
|
action = {'city': city_now, 'type': column,
|
|
'price': int((item[column])[str(i) + '.0%']), 'percent': i}
|
|
percents_actions.append(action)
|
|
|
|
percents_df = pd.DataFrame(percents_actions)
|
|
|
|
cities = consumption_aim_df['city'].unique()
|
|
actions = list()
|
|
count = 0
|
|
|
|
for city_now in cities:
|
|
log.info("开始计算:{}".format(city_now))
|
|
df = consumption_aim_df[consumption_aim_df['city'] == city_now].copy()
|
|
percents_now_df = percents_df[percents_df['city'] == city_now].copy()
|
|
try:
|
|
for i in range(1, 101):
|
|
if i == 1:
|
|
for column in columns:
|
|
df.loc[(df[column] <= percents_now_df[(percents_now_df['type'] == column) & (percents_now_df['percent'] == i)].iloc[0]['price']), column + '_percentile'] = 101 - i
|
|
else:
|
|
for column in columns:
|
|
df.loc[(df[column] > percents_now_df[(percents_now_df['type'] == column) & (percents_now_df['percent'] == i - 1)].iloc[0]['price']) & (df[column] <= percents_now_df[(percents_now_df['type'] == column) & (percents_now_df['percent'] == i)].iloc[0]['price']), column + '_percentile'] = 101 - i
|
|
except Exception as e:
|
|
log.error("解析错误{}", e)
|
|
continue
|
|
# 批量更新
|
|
for index, item in df.iterrows():
|
|
row = dict()
|
|
_id = str(item["id"])
|
|
for column in columns:
|
|
if pd.notna(item[column + '_percentile']):
|
|
if 'estate_charge_fix' == column:
|
|
db_column = "estate_charge_percentile"
|
|
else:
|
|
db_column = column + '_percentile'
|
|
row[db_column] = int(item[column + '_percentile'])
|
|
# 根据百分位计算小区规模,优先户数,然后根据建筑面积
|
|
if 'household_count_percentile' in item and pd.notna(item['household_count_percentile']):
|
|
if item['household_count_percentile'] <= 33:
|
|
row['scale'] = '小'
|
|
elif item['household_count_percentile'] <= 66:
|
|
row['scale'] = '中'
|
|
else:
|
|
row['scale'] = '大'
|
|
if 'scale' not in row:
|
|
if 'build_area_percentile' in item and pd.notna(item['build_area_percentile']):
|
|
if item['build_area_percentile'] <= 33:
|
|
row['scale'] = '小'
|
|
elif item['build_area_percentile'] <= 66:
|
|
row['scale'] = '中'
|
|
else:
|
|
row['scale'] = '大'
|
|
if 'build_area_percentile' in row:
|
|
del row['build_area_percentile']
|
|
|
|
action = {'_op_type': 'update',
|
|
'_index': index_name,
|
|
'_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))
|
|
|
|
|
|
sys_city = sys.argv[1] if len(sys.argv) > 1 else None
|
|
if pd.notna(sys_city) and "," in sys_city:
|
|
cities = sys_city.split(",")
|
|
for city in cities:
|
|
calc_percentile(city)
|
|
else:
|
|
calc_percentile(sys_city)
|