0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PandasのDataFrameでappendの代わりの方法

Posted at

PandasのDataFrameでappendの代替

FutureWarning

pandasのDataFrameに対してappendを用いると以下のような警告がされる。
いつかなくなるメソッドだからappendではなくconcatを使ってね、とのこと。

 FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version.
   Use pandas.concat instead.

appendを使用する目的

カラム名だけで値は空のDataFrameを用意して、カラムを追加していきたい。

結論

コード

# カラム名のみの空DataFrameを作成
cols = ['col_{}'.format(s) for s in range(9)]
df = pd.DataFrame(index=[], columns=cols)
# >> Empty DataFrame
# >> Columns: [col_0, col_1, col_2, col_3, col_4, col_5, col_6, col_7, col_8]
# >> Index: []

# カラムデータの作成
transaction = ['hoge'] * len(cols)
record = pd.Series(transaction, index=df.columns)

# appendの役割
df.loc[len(df)] = record

結果

  col_0 col_1 col_2 col_3 col_4 col_5 col_6 col_7 col_8
0  hoge  hoge  hoge  hoge  hoge  hoge  hoge  hoge  hoge

concat使ってないじゃんと思いますよね。僕も思いました。
むしろこのやり方って、よくIndexOutにならないなって感心してます。詳しい人いらしたらご教授いただけると幸いです。

失敗談

concatをappendの代わりに使用して、目的の動作が達成できなかったためこのようなやり方となってしまった。
concatで試してダメだったバージョンを以下に。

コード (# appendの役割 の部分をこれに変えたもの)

df = pd.concat([df, record])

結果

      col_0 col_1 col_2 col_3 col_4 col_5 col_6 col_7 col_8     0
col_0   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge
col_1   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge
col_2   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge
col_3   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge
col_4   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge
col_5   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge
col_6   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge
col_7   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge
col_8   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  hoge

多分、どこかのパラメータの指定がうまく行ってないのだとは思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?