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 5 years have passed since last update.

pandas 列へ値の代入についてのメモ書き

Posted at

はじめに

DataFrameのスライスには、直接値を代入できない。

下記のようにdf3というDataFrameがあり、
単価列のNanバリューを埋めたいという要件があったとして。

# サンプルとしてこんなDataFrameがあります。
>> df3
0	1	2	単価	price
0	0	1	2	10.0	20.0
1	3	4	5	NaN	NaN
2	6	7	8	NaN	NaN

# 単価列のNaNに0を代入したいので、、、、

>> df3[df3["単価"].isnull()][["単価"]] = 0
# と、しました。が、、、、

# Warningが表示され失敗しました。
>> /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.

Google翻訳:
DataFrameのスライスのコピーに値を設定しようとしています。
代わりに.loc [row_indexer、col_indexer] = valueを試してください。

正解

# 正解はこちらのようです。
df3.loc[df3["単価"].isnull(),["単価"]] = 0

この例の場合は、Nanバリューなのでfillna関数とか使えばいいのかもしれないのだけども。一応。

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?