回答編集履歴
1
追記
test
CHANGED
@@ -1,3 +1,77 @@
|
|
1
1
|
実現したいことというのは、下記URLのようなことでしょうか。
|
2
2
|
|
3
3
|
[pandasでカテゴリ変数をダミー変数に変換(get_dummies)](https://note.nkmk.me/python-pandas-get-dummies/)
|
4
|
+
|
5
|
+
|
6
|
+
|
7
|
+
```python3
|
8
|
+
|
9
|
+
import io
|
10
|
+
|
11
|
+
import pandas as pd
|
12
|
+
|
13
|
+
data = """name type
|
14
|
+
|
15
|
+
0 A east
|
16
|
+
|
17
|
+
1 B west
|
18
|
+
|
19
|
+
2 C east
|
20
|
+
|
21
|
+
3 A middle
|
22
|
+
|
23
|
+
4 A west
|
24
|
+
|
25
|
+
5 C east"""
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
df = pd.read_table(io.StringIO(data), delimiter="\s+")
|
30
|
+
|
31
|
+
print(df)
|
32
|
+
|
33
|
+
# name type
|
34
|
+
|
35
|
+
# 0 A east
|
36
|
+
|
37
|
+
# 1 B west
|
38
|
+
|
39
|
+
# 2 C east
|
40
|
+
|
41
|
+
# 3 A middle
|
42
|
+
|
43
|
+
# 4 A west
|
44
|
+
|
45
|
+
# 5 C east
|
46
|
+
|
47
|
+
new_df = pd.concat([df,pd.get_dummies(df['type'])],axis=1)
|
48
|
+
|
49
|
+
print(new_df)
|
50
|
+
|
51
|
+
# name type east middle west
|
52
|
+
|
53
|
+
# 0 A east 1 0 0
|
54
|
+
|
55
|
+
# 1 B west 0 0 1
|
56
|
+
|
57
|
+
# 2 C east 1 0 0
|
58
|
+
|
59
|
+
# 3 A middle 0 1 0
|
60
|
+
|
61
|
+
# 4 A west 0 0 1
|
62
|
+
|
63
|
+
# 5 C east 1 0 0
|
64
|
+
|
65
|
+
sum_df = pd.DataFrame(new_df.groupby(["name"]).sum().reset_index())
|
66
|
+
|
67
|
+
print(sum_df)
|
68
|
+
|
69
|
+
# name east middle west
|
70
|
+
|
71
|
+
# 0 A 1 1 1
|
72
|
+
|
73
|
+
# 1 B 0 0 1
|
74
|
+
|
75
|
+
# 2 C 2 0 0
|
76
|
+
|
77
|
+
```
|