【发布时间】:2020-10-25 19:11:44
【问题描述】:
读取包含自 2000 年以来巴西人口估计值的 .xls 文件, 我从 2000.xls 文件开始,它填充了一个名为 main_df 的数据框,起初看起来像
STATE STATE_CODE CITY CITY_CODE 2000_POP
SP X 圣保罗 Y 10.000.000 ...
从 2001 年到 2020 年迭代 *.xls 文件后,main_df 应如下所示:
STATE STATE_CODE CITY CITY_CODE 2000_POP 2001_POP 2002_POP ... 2020_POP SP X 圣保罗 Y 10.000.000 m n ... p ...
为了实现这一点,我以一种不太有效的方式使用 Pandas,迭代 df 行,但无论如何,这是我发现寻找城市和州代码的人口规模的方式。
作为 df 表示 2001 年至 2020 年城市人口估计的数据框。
这是代码 sn-p 迭代每个 df 行以尝试填充 main_df:
df = pd.read_excel(filename, encoding='latin_1', sep=',')
column_year_id = filename.strip('.xls')
df.columns = ['STATE', 'STATE_CODE', 'CITY', 'CITY_CODE', column_year_id]
for index, row in df.iterrows():
target_uf = (row['STATE_CODE'])
target_city_code = (str(row['CITY_CODE']))
population_on_current_year = row[-1]
selection = (main_df['STATE_CODE'] == target_uf) & (main_df['CITY_CODE'] == target_city_code)
main_df.loc[selection, column_year_id] = population_on_current_year
问题在于,在一天结束时,main_df 最终只填充了原来的 2000 人口规模列,但是,从 2001 年到 2020 年,它填充了 NaN 值,如下所示:
STATE STATE_CODE CITY CITY_CODE 2000_POP 2001_POP 2002_POP ... 2020_POP SP X 圣保罗 Y 10.000.000 NaN NaN ... NaN ...
为什么会发生,我应该怎么做才能让它发挥作用?
问题似乎是因为我无法将元素插入到特定位置,例如 main_df 是使用 main_df[index, column] 的数组。 Pandas 允许这种插入方式吗?
编辑 1: 这就是我创建 main_df 的方式:
main_df = pd.read_excel(filename, encoding='latin_1', sep=',')
【问题讨论】:
-
你能分享你创建`main_df`的代码吗?您是否尝试使用 pd.join 函数而不是 iterrows?
-
是的,我做到了,但问题是我需要阅读目标 df 的每一行,才能按州按城市名称查找该年的城市人口。它看起来像一个 SQL 查询。无论如何,我已经找到了我想要的答案。谢谢。
标签: python pandas dataframe nan