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

DateFrameを2つのkeyで昇順にソートする方法

Last updated at Posted at 2021-02-26

#1 この記事は何?

DateFarme型を2つのkeyで昇順に並べ替える方法を節毎します。

下記は、行名Aを第1keyで昇順に並べ替え、行名Dateを第2Keyで昇順に並べ替えをしています。
image.png

#2 どうやってやるの?

下記のコードの通り実施してみてください。

example
import pandas as pd
import numpy as np
import scipy.stats
idx = pd.IndexSlice

#dataを定義する。
dat = [
    [1,'2019-07-01',2],
    [1,'2019-09-02',4],
    [1,'2019-06-01',8],
    [3,'2018-07-02',16],    
    [3,'2019-07-03',100],
    [3,'2016-07-01',200],
    [2,'2020-07-01',400],
    [2,'2019-07-01',200],    
]

#datをDataFrame型変数dfに格納する。
df = pd.DataFrame(dat,columns=["A","Date","C"])
print("df",df)

print("第1keyを「A」、第2keyを「Date」で並べ替える。")
df1 = df.sort_values(['A', 'Date'],ascending = True)
df1

実行結果

example
df    A        Date    C
0  1  2019-07-01    2
1  1  2019-09-02    4
2  1  2019-06-01    8
3  3  2018-07-02   16
4  3  2019-07-03  100
5  3  2016-07-01  200
6  2  2020-07-01  400
7  2  2019-07-01  200

第1keyを「A」、第2keyを「Date」で並べ替える。
        A	Date	C
0	1	2019-06-01	8
1	1	2019-07-01	2
2	1	2019-09-02	4
3	2	2019-07-01	200
4	2	2020-07-01	400
5	3	2016-07-01	200
6	3	2018-07-02	16
7	3	2019-07-03	100
0
0
2

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?