環境
- Python 3.10.2
- pandas 1.5.3
やりたいこと
pandas.DataFrame.pivot_table
を使って、以下のような集計を行いたいです。
>>> df = pandas.DataFrame(
{
"count": [1, 2, 3, 4],
"phase": ["A", "A", "B", "B"],
"user_id": ["alice", "alice", "alice", "bob"],
})
>>> df
count phase user_id
0 1 A alice
1 2 A alice
2 3 B alice
3 4 B bob
>>> df.dtypes
count int64
phase object
user_id object
dtype: object
>>> df.pivot_table(values="count", columns="phase", index="user_id", aggfunc=numpy.sum)
phase A B
user_id
alice 3.0 3.0
bob NaN 4.0
起きたこと
空のDataFrameに対してpivot_tableメソッドを実行したところ、「If any error is raised, this will raise an exception in a future version of pandas. Drop these columns to avoid this warning.」という警告が発生しました。
警告メッセージの内容はよく分かりませんでした。
>>> df_empty = pandas.DataFrame(columns=["count","phase","user_id"])
>>> df_empty
Empty DataFrame
Columns: [count, phase, user_id]
Index: []
>>> df_empty.dtypes
count object
phase object
user_id object
dtype: object
>>> df_empty.pivot_table(values="count", columns="phase", index="user_id", aggfunc=numpy.sum)
<ipython-input-64-c704905fca9d>:1: FutureWarning: The operation <function sum at 0x7f1ba2d8edd0> failed on a column. If any error is raised, this will raise an exception in a future version of pandas. Drop these columns to avoid this warning.
df_empty.pivot_table(values="count", columns="phase", index="user_id", aggfunc=numpy.sum)
Empty DataFrame
Columns: []
Index: []
対策
count
列の型をobjectからint64に変更したら、警告は出なくなりました。なぜ列の型を変更したら、警告が出なくなったのかは分かりません。。。列の型の指定は間違っていないので、問題はないでしょう。
>>> df_empty2 = df_empty.astype({"count":"int64"})
>>> df_empty2.dtypes
count int64
phase object
user_id object
dtype: object
>>> df_empty2.pivot_table(values="count", columns="phase", index="user_id", aggfunc=numpy.sum)
Empty DataFrame
Columns: []
Index: []