想定データ
以下の人口統計データ。
市区町村名がNaNになっているところに、都道府県名を入れたい。
団体コード 都道府県名 市区町村名 性別 総数 0~4歳 5~9 10~14 15~19 \
3 10006.0 北海道* NaN 計 5339539 181591 201119 213206 231870
4 10006.0 北海道* NaN 男 2522526 93048 102850 108783 118414
5 10006.0 北海道* NaN 女 2817013 88543 98269 104423 113456
6 11002.0 北海道 札幌市 計 1952348 71281 75025 76342 82644
7 11002.0 北海道 札幌市 男 913077 36715 38250 38839 41729
コード
df['市区町村名'].fillna(df['都道府県名'], inplace=True)
# こちらでも可能ですが、遅くなるようです。
df.loc[pd.isnull(df['市区町村名']), ['市区町村名']] = df['都道府県名']
失敗したコード
for i, (prefecture, city) in enumerate(zip(df['都道府県名'], df['市区町村名'])):
if pd.isnull(city):
df['市区町村名'][i] = prefecture
結果
<ipython-input-59-8ff91f161741>:3: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
df['市区町村名'][i] = prefecture
参考
-
DataFrameの値の更新 - pandas [いかたこのたこつぼ]
- Forループなど無邪気に実装するとSettingWithCopyWarningが出てしまう