1.condition
import json
import sys
import pandas as pd
pd.set_option('display.max_columns', None)
cbg_features_df = pd.read_csv('cbg_features_2019.csv')
with open('cbg_lonlat_dict.json', 'r', encoding='utf-8') as f:
cbg_lonlat_dict = json.load(f)
cbg_lonlat_dict_keys_list = list(cbg_lonlat_dict.keys())
int_list = [int(x) for x in cbg_lonlat_dict_keys_list]
cbg_total_population_list = []
for a in int_list:
condition = cbg_features_df['census_block_group'] == a
total_population = cbg_features_df[condition]['Total population'].iloc[0]
cbg_total_population_list.append(total_population)
cbg_activate_df = pd.DataFrame({'cbg_id': cbg_lonlat_dict_keys_list, 'cbg_total_people': cbg_total_population_list})
print(cbg_activate_df)
核心代码其实就是这两行:
condition = cbg_features_df['census_block_group'] == a
total_population = cbg_features_df[condition]['Total population'].iloc[0]
2.merge
import json
import sys
import pandas as pd
pd.set_option('display.max_columns', None)
cbg_features_df = pd.read_csv('cbg_features_2019.csv')
with open('cbg_lonlat_dict.json', 'r', encoding='utf-8') as f:
cbg_lonlat_dict = json.load(f)
cbg_lonlat_dict_keys_list = list(cbg_lonlat_dict.keys())
int_list = [int(x) for x in cbg_lonlat_dict_keys_list]
cbg_activate_df = pd.merge(pd.DataFrame({'census_block_group': int_list}), cbg_features_df, on='census_block_group', how='left')
cbg_activate_df = cbg_activate_df[['census_block_group', 'Total population']]
print(cbg_activate_df)
可以看到merge方法在做此类问题的时候比较优雅,核心代码列出如下:
cbg_activate_df = pd.merge(pd.DataFrame({'census_block_group': int_list}), cbg_features_df, on='census_block_group', how='left')
cbg_activate_df = cbg_activate_df[['census_block_group', 'Total population']]