LoginSignup
0
1

More than 3 years have passed since last update.

Pandas備忘録

Last updated at Posted at 2020-08-23

概要

Pandasで個人的に覚えておきたいこと一覧
随時更新します

課題一覧

1. カラムが複数行存在する際に、2行目をカラム名とする方法

2. 複数行のカラムの読み込み

3. indexの重複削除

4. 行の入れ替え

5. 時系列データの補間

方法

1・2用のサンプルcsv

Japan America
month start end worktime memo month start end worktime memo
20200408 900 1730 8.5 hello 20200408 900 1730 8.5 hello

1. カラムが複数行存在する際に、2行目をカラム名とする方法

df.columns=df.loc[0,:]
df.drop(0,axis=0)

②(推奨)

df = pd.read_csv("./excel-sample1.csv", skiprows=1)

2. 複数行のカラムの読み込み

df = pd.read_csv("./excel-sample1.csv", header=[0,1])

コラム

  • 複数行カラムの扱い方
print(df.loc[:,'Unnamed: 1_level_0'])
df.loc[:,('Unnamed: 1_level_0','start')]
# ずれるとダメ
df.loc[:,('Unnamed: 1_level_0','end')]

3・4用のサンプルcsv

a b c
1 4 NaN
2 5 NaN
3 6 NaN
1 4 NaN
2 3 4.0

3. indexの重複削除

df_sample.loc[~df_sample.index.duplicated(keep='first')]
  • 先頭を残すならfirst、後ろを残すならlast

4. 行の入れ替え

df_sample.iloc[[0,1,4,2,3],:]
  • この場合、indexは0, 1, 1, 2, NaNの順

5用のサンプルcsv

datetime id sample1 sample2
2020/10/14 15:00 4 132 k
2020/10/14 15:15 4 144 l
2020/10/14 15:30 5 156 n
2020/10/14 15:45 5 168 m
2020/10/14 16:00 5 180 abc
2020/10/14 16:15 6 192 def
2020/10/14 16:30 6 204 ghi
2020/10/24 13:45 6 205 fgh
2020/10/25 13:45 6 206 fgd
2020/10/26 13:45 6 207 asd

5. 時系列データの補間

df["datetime"] = pd.to_datetime(df["datetime"]) # 一応
df2 = df.set_index('datetime') 
df3 = df2.resample('15T').mean()
df3["datetime"] = df3.index # インデックスから列に戻す(一応)
df3.reset_index(drop = True, inplace=True) # インデックスを振る(一応)
  • 時刻を補間することで、元々のデータに存在しない時刻の線プロット補間を回避できる
0
1
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
1