<前回>
机を配置しようぜ☆(^~^)?
Git hub: practice-pandas
「 データを集計したかっただけなんだが、 Python3 には pandas というライブラリがあるらしい……☆」
「 3分って待ち時間なんだな☆ コマンド1発でインストールでけた☆」
1,Red
2,Red
3,Blue
4,Blue
5,Green
6,Blue
7,Red
8,Blue
9,Green
10,Green
11,Purple
12,Red
13,Violet
14,Green
15,Blue
16,Yellow
17,Blue
18,Yellow
19,SkyBlue
20,Yellow
21,Red
22,Blue
23,Black
24,Black
25,White
26,Yellow
27,Blue
28,Pink
29,Green
30,Blue
31,Yellow
32,Orange
33,Blue
34,Pink
35,Gray
36,Green
37,Red
38,Orange
39,White
40,Blue
41,Red
42,Green
43,Yellow
44,Green
45,YellowGreen
46,Black
47,Brown
48,White
49,Gray
50,Blue
51,Yellow
52,Red
53,Green
54,Orange
55,Violet
56,Blue
57,Green
58,Yellow
59,White
60,Blue
「 これを Red 何件、Blue 何件、と集計して 多い順に並べたいだけなんだが☆」
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',')
# df = pd.read_csv("./data/test-participant.csv", sep=',')
# データの確認をする(最初の3行を表示)
df.head(3)
Unable to open 'parsers.pyx': Unable to read file (Error: File not found (c:\users\むずでょ\onedrive\ドキュメント\math-py\pandas\_libs\parsers.pyx)).
「 pandas というディレクトリーなどないのだから、エラーが出て当然だろう☆」
C:\Users\むずでょ\AppData\Local\Programs\Python\Python37\Lib\site-packages\pandas
PS C:\Users\むずでょ\OneDrive\ドキュメント\math-py> cd 'c:\Users\むずでょ\OneDrive\ドキュメント\math-py'; ${env:PYTHONIOENCODING}='UTF-8'; ${env:PYTHONUNBUFFERED}='1'; & 'C:\Users\むずでょ\AppData\Local\Programs\Python\Python37\pon\Python37\python.exe' 'c:\Users\むずでょ\.vscode\extensions\ms-python.python-2019.6.24221\pythonFiles\ptvsd_launcher.py' '--default' '--client' '--host' 'localhost' '--port' '52411' 'c:\Users\むずでょ\OneDrive\ドキントth-ctice-ュメント\math-py\practice-pandas\go.py'
「 cd
(change directory) してないか☆?」
「 Visual Studio Code のデバッガーで動かすと いつも実行スクリプトがあるディレクトリに cd
してるぜ☆」
「 cd
しようと しまいと、標準ディレクトリにある pandas は何で 見つからないわけ?」
import pandas as pd
print(pd.__version__)
print("Info : Finished.")
0.24.2
Info : Finished.
「 pandas は見えてるはずだぜ☆
read_csv
が おかしいのでは☆?」
「 すぐ 問題の切り分けに動いて 原因を特定するのが早い☆」
Visual Studio Code windows , Python Pandas . No module named pandas
PS C:\Users\むずでょ\OneDrive\ドキュメント\math-py> pip install pandas
Requirement already satisfied: pandas in c:\users\むずでょ\appdata\local\programs\python\python37\lib\site-packages (0.24.2)
Requirement already satisfied: python-dateutil>=2.5.0 in c:\users\むずでょ\appdata\local\programs\python\python37\lib\site-packages (from pandas) (2.8.0)
Requirement already satisfied: numpy>=1.12.0 in c:\users\むずでょ\appdata\local\programs\python\python37\lib\site-packages (from pandas) (1.16.4)
Requirement already satisfied: pytz>=2011k in c:\users\むずでょ\appdata\local\programs\python\python37\lib\site-packages (from pandas) (2019.1)
Requirement already satisfied: six>=1.5 in c:\users\むずでょ\appdata\roaming\python\python37\site-packages (from python-dateutil>=2.5.0->pandas) (1.12.0)
「 read_csv は、このパスを見に行ってないのか☆?」
windows上のjupyter、python で csvファイルを読み込むまで
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',', engine='python')
# データの確認をする(最初の3行を表示)
df.head(3)
print("Info : Finished.")
Info : Finished.
# データの確認をする(最初の3行を表示)
print(df.head(3))
# df.head(3)
1 Red
0 2 Red
1 3 Blue
2 4 Blue
Info : Finished.
「 くそサイト のことは もう忘れた☆
それより 1行 ずれたみたいに表示されてるのは なんでだぜ☆?」
ID GENRE_CODE
0 1 Red
1 2 Red
2 3 Blue
3 4 Blue
4 5 Green
Info : Finished.
「 pandas と SQL の比較サイトみたいなのは 無いのかだぜ☆?」
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',', engine='python', verbose=True)
df_grouped = df.groupby("GENRE_CODE").count()
df_sorted = df_grouped["ID"].sort_values(ascending=False)
# Top 1000.
# print(df.head(1000))
print(df_sorted.head(1000))
# print(pd.__version__)
print("Info : Finished.")
GENRE_CODE
Blue 14
Green 10
Yellow 8
Red 8
White 4
Orange 3
Black 3
Violet 2
Pink 2
Gray 2
YellowGreen 1
SkyBlue 1
Purple 1
Brown 1
Name: ID, dtype: int64
Info : Finished.
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',', engine='python', verbose=True)
df_sorted = df["GENRE_CODE"].sort_values(ascending=False)
# Top 1000.
print(df_sorted.head(1000))
print("Info : Finished.")
44 YellowGreen
57 Yellow
30 Yellow
15 Yellow
17 Yellow
19 Yellow
50 Yellow
25 Yellow
42 Yellow
58 White
38 White
24 White
47 White
12 Violet
54 Violet
18 SkyBlue
0 Red
6 Red
# 以下略
「 やりたいことは 順番に1つずつ行こう☆
グループ名に、要素数の多い順位を付けようぜ☆」
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',', engine='python', verbose=True)
df["RANK"] = 0
# Top 1000.
print(df.head(1000))
print("Info : Finished.")
ID GENRE_CODE RANK
0 1 Red 0
1 2 Red 0
2 3 Blue 0
3 4 Blue 0
4 5 Green 0
5 6 Blue 0
6 7 Red 0
7 8 Blue 0
# 以下略
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',', engine='python', verbose=True)
df = df.rank()
# Top 1000.
print(df.head(1000))
print("Info : Finished.")
ID GENRE_CODE
0 1.0 40.5
1 2.0 40.5
2 3.0 10.5
3 4.0 10.5
4 5.0 25.5
5 6.0 10.5
6 7.0 40.5
7 8.0 10.5
8 9.0 25.5
9 10.0 25.5
10 11.0 36.0
Python DataFrame:ランキング順で番号を割り振るようにしたい
'DataFrame' object has no attribute 'sort'
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',', engine='python')
df = df.rank()
df2 = df.groupby('GENRE_CODE').size().rank(
ascending=False,
method='first'
).astype(int).reset_index(name='RANK')
df = df.merge(df2, right_index=True, on='GENRE_CODE').sort_index()
# Top 1000.
print(df.head(1000))
print("Info : Finished.")
ID GENRE_CODE RANK
0 1.0 40.5 3
1 2.0 40.5 3
2 3.0 10.5 1
3 4.0 10.5 1
4 5.0 25.5 2
5 6.0 10.5 1
6 7.0 40.5 3
7 8.0 10.5 1
8 9.0 25.5 2
9 10.0 25.5 2
10 11.0 36.0 12
11 12.0 40.5 3
12 13.0 46.5 10
13 14.0 25.5 2
# 以下略
「 GENRE_CODE の 40.5 とかいう分けわからん数を 表結合のキーにしているので、元表とは くっつかないぜ☆」
df["RANK"] = df["GENRE_CODE"]
ID GENRE_CODE RANK
0 1 Red Red
1 2 Red Red
2 3 Blue Blue
3 4 Blue Blue
4 5 Green Green
5 6 Blue Blue
6 7 Red Red
7 8 Blue Blue
# 以下略
「 ダメだ、列が増えても .rank は 全列を変な数にしてしまう☆」
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',', engine='python')
df2 = df.assign(RANK=df["GENRE_CODE"].rank())
print(df2.head(1000))
print("Info : Finished.")
ID GENRE_CODE RANK
0 1 Red 40.5
1 2 Red 40.5
2 3 Blue 10.5
3 4 Blue 10.5
4 5 Green 25.5
5 6 Blue 10.5
6 7 Red 40.5
7 8 Blue 10.5
8 9 Green 25.5
9 10 Green 25.5
10 11 Purple 36.0
11 12 Red 40.5
pandas.DataFrameに列や行を追加(assign, appendなど)
ID GENRE_CODE RANK_x RANK_y
0 1 Red 40.5 3
1 2 Red 40.5 3
2 3 Blue 10.5 1
3 4 Blue 10.5 1
「 merge で同名の列があると 名前の後ろに _x
とか _y
が付くみたいだな☆
じゃあ 列を消す方法を探そうぜ☆」
df2 = df2.drop("RANK", axis=1)
ID GENRE_CODE RANK
0 1 Red 3
1 2 Red 3
2 3 Blue 1
3 4 Blue 1
4 5 Green 2
5 6 Blue 1
6 7 Red 3
7 8 Blue 1
8 9 Green 2
9 10 Green 2
10 11 Purple 12
11 12 Red 3
import os
import pandas as pd
df = pd.read_csv(
"{}/practice-pandas/data/test-participant.csv".format(os.getcwd()), sep=',', engine='python')
df2 = df.assign(RANK=df["GENRE_CODE"].rank())
# print(df.head(1000))
"""
ID GENRE_CODE RANK
0 1 Red 40.5
1 2 Red 40.5
2 3 Blue 10.5
3 4 Blue 10.5
4 5 Green 25.5
5 6 Blue 10.5
6 7 Red 40.5
7 8 Blue 10.5
8 9 Green 25.5
9 10 Green 25.5
10 11 Purple 36.0
11 12 Red 40.5
12 13 Violet 46.5
13 14 Green 25.5
14 15 Blue 10.5
15 16 Yellow 55.5
16 17 Blue 10.5
17 18 Yellow 55.5
18 19 SkyBlue 45.0
19 20 Yellow 55.5
20 21 Red 40.5
21 22 Blue 10.5
22 23 Black 2.0
23 24 Black 2.0
24 25 White 49.5
25 26 Yellow 55.5
26 27 Blue 10.5
27 28 Pink 34.5
28 29 Green 25.5
29 30 Blue 10.5
30 31 Yellow 55.5
31 32 Orange 32.0
32 33 Blue 10.5
33 34 Pink 34.5
34 35 Gray 19.5
35 36 Green 25.5
36 37 Red 40.5
37 38 Orange 32.0
38 39 White 49.5
39 40 Blue 10.5
40 41 Red 40.5
41 42 Green 25.5
42 43 Yellow 55.5
43 44 Green 25.5
44 45 YellowGreen 60.0
45 46 Black 2.0
46 47 Brown 18.0
47 48 White 49.5
48 49 Gray 19.5
49 50 Blue 10.5
50 51 Yellow 55.5
51 52 Red 40.5
52 53 Green 25.5
53 54 Orange 32.0
54 55 Violet 46.5
55 56 Blue 10.5
56 57 Green 25.5
57 58 Yellow 55.5
58 59 White 49.5
59 60 Blue 10.5
"""
df3 = df2.groupby('GENRE_CODE').size().rank(
ascending=False,
method='first'
).astype(int).reset_index(name='RANK')
# print(df3.head(1000))
"""
GENRE_CODE RANK
0 Black 6
1 Blue 1
2 Brown 11
3 Gray 8
4 Green 2
5 Orange 7
6 Pink 9
7 Purple 12
8 Red 3
9 SkyBlue 13
10 Violet 10
11 White 5
12 Yellow 4
13 YellowGreen 14
"""
df2 = df2.drop("RANK", axis=1)
df2 = df2.merge(df3, right_index=True, on='GENRE_CODE').sort_index()
# print(df2.head(1000))
"""
ID GENRE_CODE RANK
0 1.0 40.5 3
1 2.0 40.5 3
2 3.0 10.5 1
3 4.0 10.5 1
4 5.0 25.5 2
5 6.0 10.5 1
6 7.0 40.5 3
7 8.0 10.5 1
8 9.0 25.5 2
9 10.0 25.5 2
10 11.0 36.0 12
11 12.0 40.5 3
12 13.0 46.5 10
13 14.0 25.5 2
14 15.0 10.5 1
15 16.0 55.5 4
16 17.0 10.5 1
17 18.0 55.5 4
18 19.0 45.0 13
19 20.0 55.5 4
20 21.0 40.5 3
21 22.0 10.5 1
22 23.0 2.0 6
23 24.0 2.0 6
24 25.0 49.5 5
25 26.0 55.5 4
26 27.0 10.5 1
27 28.0 34.5 9
28 29.0 25.5 2
29 30.0 10.5 1
30 31.0 55.5 4
31 32.0 32.0 7
32 33.0 10.5 1
33 34.0 34.5 9
34 35.0 19.5 8
35 36.0 25.5 2
36 37.0 40.5 3
37 38.0 32.0 7
38 39.0 49.5 5
39 40.0 10.5 1
40 41.0 40.5 3
41 42.0 25.5 2
42 43.0 55.5 4
43 44.0 25.5 2
44 45.0 60.0 14
45 46.0 2.0 6
46 47.0 18.0 11
47 48.0 49.5 5
48 49.0 19.5 8
49 50.0 10.5 1
50 51.0 55.5 4
51 52.0 40.5 3
52 53.0 25.5 2
53 54.0 32.0 7
54 55.0 46.5 10
55 56.0 10.5 1
56 57.0 25.5 2
57 58.0 55.5 4
58 59.0 49.5 5
59 60.0 10.5 1
"""
df2 = df2.drop("ID", axis=1)
# print(df2.head(1000))
df_grouped = df2.groupby("GENRE_CODE").count()
"""
print(df_grouped.head(1000))
RANK
GENRE_CODE
Black 3
Blue 14
Brown 1
Gray 2
Green 10
Orange 3
Pink 2
Purple 1
Red 8
SkyBlue 1
Violet 2
White 4
Yellow 8
YellowGreen 1
"""
df_sorted = df_grouped["RANK"].sort_values(ascending=True)
print(df_sorted.head(1000))
"""
GENRE_CODE
Brown 1
Purple 1
SkyBlue 1
YellowGreen 1
Gray 2
Pink 2
Violet 2
Black 3
Orange 3
White 4
Red 8
Yellow 8
Green 10
Blue 14
Name: RANK, dtype: int64
"""
print("Info : Finished.")
「 このテーブルを利用して、参加者ID を並び替えようぜ☆?」
「 SQLだと Join を使えばいいが、 pandas は .merge を使うんだろうか☆?」
df4 = df.merge(df_grouped, right_index=True, on='GENRE_CODE')
print(df4.head(1000))
ID GENRE_CODE RANK
0 1 Red 8
1 2 Red 8
6 7 Red 8
11 12 Red 8
20 21 Red 8
36 37 Red 8
40 41 Red 8
51 52 Red 8
2 3 Blue 14
3 4 Blue 14
5 6 Blue 14
7 8 Blue 14
14 15 Blue 14
16 17 Blue 14
21 22 Blue 14
26 27 Blue 14
29 30 Blue 14
32 33 Blue 14
39 40 Blue 14
49 50 Blue 14
55 56 Blue 14
59 60 Blue 14
4 5 Green 10
8 9 Green 10
9 10 Green 10
13 14 Green 10
28 29 Green 10
35 36 Green 10
41 42 Green 10
43 44 Green 10
52 53 Green 10
56 57 Green 10
10 11 Purple 1
12 13 Violet 2
54 55 Violet 2
15 16 Yellow 8
17 18 Yellow 8
19 20 Yellow 8
25 26 Yellow 8
30 31 Yellow 8
42 43 Yellow 8
50 51 Yellow 8
57 58 Yellow 8
18 19 SkyBlue 1
22 23 Black 3
23 24 Black 3
45 46 Black 3
24 25 White 4
38 39 White 4
47 48 White 4
58 59 White 4
27 28 Pink 2
33 34 Pink 2
31 32 Orange 3
37 38 Orange 3
53 54 Orange 3
34 35 Gray 2
48 49 Gray 2
44 45 YellowGreen 1
46 47 Brown 1
df_sorted = df4.sort_values('RANK', ascending=False)
print(df_sorted.head(1000))
ID GENRE_CODE RANK
29 30 Blue 14
5 6 Blue 14
55 56 Blue 14
49 50 Blue 14
39 40 Blue 14
32 33 Blue 14
26 27 Blue 14
21 22 Blue 14
16 17 Blue 14
14 15 Blue 14
7 8 Blue 14
3 4 Blue 14
2 3 Blue 14
59 60 Blue 14
4 5 Green 10
9 10 Green 10
13 14 Green 10
8 9 Green 10
28 29 Green 10
35 36 Green 10
41 42 Green 10
43 44 Green 10
52 53 Green 10
56 57 Green 10
15 16 Yellow 8
19 20 Yellow 8
25 26 Yellow 8
30 31 Yellow 8
42 43 Yellow 8
50 51 Yellow 8
57 58 Yellow 8
17 18 Yellow 8
0 1 Red 8
6 7 Red 8
1 2 Red 8
51 52 Red 8
40 41 Red 8
36 37 Red 8
20 21 Red 8
11 12 Red 8
58 59 White 4
47 48 White 4
38 39 White 4
24 25 White 4
53 54 Orange 3
45 46 Black 3
23 24 Black 3
22 23 Black 3
31 32 Orange 3
37 38 Orange 3
34 35 Gray 2
48 49 Gray 2
12 13 Violet 2
33 34 Pink 2
27 28 Pink 2
54 55 Violet 2
18 19 SkyBlue 1
10 11 Purple 1
44 45 YellowGreen 1
46 47 Brown 1
「 これで 最大ジャンルから順に 参加者IDを並べれたんじゃないか☆?」
「 SQLなら SELECT文で1件ずつ 引っこ抜く感じかだぜ☆?」
person = df4[df4.ID == 1]
print("Person: {}".format(person))
print(df4[["ID"]])
ID
0 1
1 2
6 7
11 12
20 21
36 37
40 41
51 52
2 3
3 4
5 6
# 以下略
pandas.DataFrame, SeriesとPython標準のリストを相互に変換
print(df4[["ID"]].values.tolist())
[[1], [2], [7], [12], [21], [37], [41], [52], [3], [4], [6], [8], [15], [17], [22], [27], [30], [33], [40], [50], [56], [60], [5], [9], [10], [14], [29], [36], [42], [44], [53], [57], [11],
[13], [55], [16], [18], [20], [26], [31], [43], [51], [58], [19], [23], [24], [46], [25], [39], [48], [59], [28], [34], [32], [38], [54], [35], [49], [45], [47]]
「 データを Python3 のリストで取りだしたあとなんだが……☆」
import pandas as pd
from attribute.query_id_sorted_table import query_id_sorted_table
#
# Note.
#
# Root directory: Visual studio code workspace root.
#
file_name = "./html-generator/auto-generated/view.html"
df = pd.read_csv("./html-generator/data/participant.csv",
sep=',', engine='python')
# Record set.
rs = query_id_sorted_table("./html-generator/data/participant.csv")
print(rs)
"""
[[30, 'Blue'], [6, 'Blue'], [56, 'Blue'], [50, 'Blue'], [40, 'Blue'], [33, 'Blue'], [27, 'Blue'], [22, 'Blue'], [17, 'Blue'], [15, 'Blue'], [8, 'Blue'], [4, 'Blue'], [3, 'Blue'], [60, 'Blue'], [5, 'Green'], [10, 'Green'], [14, 'Green'], [9, 'Green'], [29, 'Green'], [36, 'Green'], [42, 'Green'], [44, 'Green'], [53, 'Green'], [57, 'Green'], [16, 'Yellow'], [20, 'Yellow'], [26, 'Yellow'], [31, 'Yellow'], [43, 'Yellow'], [51, 'Yellow'], [58, 'Yellow'], [18, 'Yellow'], [1, 'Red'], [7, 'Red'], [2, 'Red'], [52, 'Red'], [41, 'Red'], [37, 'Red'], [21, 'Red'], [12, 'Red'], [59, 'White'], [48, 'White'], [39, 'White'], [25, 'White'], [54, 'Orange'], [46, 'Black'], [24, 'Black'], [23, 'Black'], [32, 'Orange'], [38, 'Orange'], [35, 'Gray'], [49, 'Gray'], [13, 'Violet'], [34, 'Pink'], [28, 'Pink'], [55, 'Violet'], [19, 'SkyBlue'], [11, 'Purple'], [45, 'YellowGreen'], [47, 'Brown']]
"""
def get_boxes(rs):
html = []
for record in rs:
html.append(
"""
<div id="box{}">
</div>
""".format(record[0])
)
return "".join(html)
「 record[0]
みたいな感じで インデックス・アクセス するのは いけてないだろ☆
クエリーで列の順番を変えたいことなんて いくらでもあるのに☆
record["ID"]
みたいに列名でアクセスしたいだろ☆」
「 列まで絞り込んでから Python3 のリストに変換したらどうだぜ☆?」
# BAD CODE
# Record set.
rs = query_rank12()
for record in rs:
id = record["ID"]
genre_code = record["GENRE_CODE"]
print("Record id:{}, genre_code:{}.".format(id, genre_code))
「 一見 こう書きたいんだが、rs
は 列を複数個持っていて、record には列名の文字列が入ってしまう☆」
「 pandas recordset
といったキーワードでググり、出てきた記事を眺めていこうぜ☆」
「 出てこなければ検索キーワードを変えろだぜ、 pandas foreach record
とか☆」
「 ツイッターのタイムラインのみんな 単語のボキャブラリーで 調査力が変わることは 知られてないよな☆
グーグルさえあれば 誰でも何でもできる、ぐらいに思われているのだろう☆」
pandas.DataFrameのforループ処理(イテレーション)
「 DataFrame.iterrows()メソッド
が使えそうだぜ☆」
# Data frame. (NOT Record set)
df = query_rank12()
for index, row in df.iterrows():
id = row["ID"]
genre_code = row["GENRE_CODE"]
print("Record id:{}, genre_code:{}.".format(id, genre_code))
print("Info : Finished.")
Record id:30, genre_code:Blue.
Record id:6, genre_code:Blue.
Record id:56, genre_code:Blue.
Record id:50, genre_code:Blue.
Record id:40, genre_code:Blue.
Record id:33, genre_code:Blue.
Record id:27, genre_code:Blue.
Record id:22, genre_code:Blue.
Record id:17, genre_code:Blue.
Record id:15, genre_code:Blue.
<続き>
机を配置しようぜ☆(^~^)?
Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?
コメント