はじめに/結論
2022年1月、Pandasのバージョンが、1.3.xから1.4へと上がった。それにともない、DataFrame.append()
が非推奨となった。使うと次のような警告が出る:
FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
DataFrame.append()
は将来的に廃止されるため、代わりにpandas.concat()
を使おう、という警告である。
DataFrame df
の列名(columns)と同じindexを持つSeries sr
を追記していくために、df = df.append(sr, ignore_index=True)
みたいに書いていたのでちょっと困った。
まあでも、df = pd.concat([df, sr])], ignore_index=True)
と書き換えれば連結されるんでしょう、と思ったら、想定とちょっと違う挙動だった。
結論を言うと、Series sr
をDataFrameに変換することで解決した。こんな感じ: df = pd.concat([df, pd.DataFrame([sr])], ignore_index=True)
df = pd.concat([df, sr])])
だとこうなる
import pandas as pd
df = pd.DataFrame(
data={'名前': ['りんご', 'なし', 'ぶどう'],
'数量': [10, 20, 30],
'単価': [100, 200, 300]}
)
df
:
名前 | 数量 | 単価 | |
---|---|---|---|
0 | りんご | 10 | 100 |
1 | なし | 20 | 200 |
2 | ぶどう | 30 | 300 |
ここにこうしてみても、
sr = pd.Series(data=['ライチ', 40, 400], index=["名前", "数量", "単価"])
df = pd.concat([df, sr], ignore_index=True)
df
:
名前 | 数量 | 単価 | 0 | |
---|---|---|---|---|
0 | りんご | 10 | 100 | NaN |
1 | なし | 20 | 200 | NaN |
2 | ぶどう | 30 | 300 | NaN |
名前 | NaN | NaN | NaN | ライチ |
数量 | NaN | NaN | NaN | 40 |
単価 | NaN | NaN | NaN | 400 |
こうなってしまう。
Seriesのindexが、DataFrameのindex(行のラベル)と結びついてしまうためだ。元のDataFrameのindexは0,1,2
であり、追加しようとしたSereisのindexは名前・数量・単価
なので新しい行を作るしかないということだ。行き場を失ったsr
は、df
の新たな列(ラベルは0)として連結される。
これはもう問答無用でSeriesをDataFrameに変換してしまってからpd.concat()
すればいいのかなと思ったらうまく行った。しかもDataFrame.append()
を使っていたときより高速に動くようになった。
df = pd.concat([df, pd.DataFrame([sr])], ignore_index=True)
df
:
名前 | 数量 | 単価 | |
---|---|---|---|
0 | りんご | 10 | 100 |
1 | なし | 20 | 200 |
2 | ぶどう | 30 | 300 |
3 | ライチ | 40 | 400 |
(pandasに精通しているわけではないので、もっといいやり方はあるかも知れません)