3
2

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 困ったことまとめ

Last updated at Posted at 2019-02-10

よく調べるので自分用にメモします

DataFrameで特定列の値がリストに含まれる行だけを抽出

import pandas as pd
df = pd.DataFrame({'N1': [1, 2, 3, 4, 5, 6],
                   'N2': [10, 20, 30, 40, 50, 60],
                   'N3': [6, 5, 4, 3, 2, 1]},
                  columns=['N1', 'N2', 'N3'])
df
#   N1  N2  N3
# 0   1  10   6
# 1   2  20   5
# 2   3  30   4
# 3   4  40   3
# 4   5  50   2
# 5   6  60   1

pandas.DataFrame.isin(list)を使用してN1列の値のうちmaskに含まれる行だけを抽出

mask = [1, 3, 5]
df[df['N1'].isin(mask)]
#    N1  N2  N3
# 0   1  10   6
# 2   3  30   4
# 4   5  50   2

DataFrameで条件に合う行に新しい列を追加する(条件に合わないところはNaN)

df.loc[条件, 新しい列の名前]=valueという風に代入していく

df.loc[df['N1']==1, 'N4']=1000
df
#    N1  N2  N3      N4
# 0   1  10   6  1000.0
# 1   2  20   5     NaN
# 2   3  30   4     NaN
# 3   4  40   3     NaN
# 4   5  50   2     NaN
# 5   6  60   1     NaN
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?