回答編集履歴

1

サンプル追加

2020/01/21 16:40

投稿

magichan
magichan

スコア15898

test CHANGED
@@ -71,3 +71,115 @@
71
71
  df.to_csv('output.csv')
72
72
 
73
73
  ```
74
+
75
+
76
+
77
+ ---
78
+
79
+ **【追加】**
80
+
81
+ frame number 集計部を追加したサンプル
82
+
83
+ ```Python
84
+
85
+ import pandas as pd
86
+
87
+ import re
88
+
89
+ from pprint import pprint
90
+
91
+
92
+
93
+ # ファイル読み込み
94
+
95
+ with open('data.txt') as f:
96
+
97
+ text = f.read()
98
+
99
+
100
+
101
+ # 正規表現を使ってデータを抜き出す
102
+
103
+ pattern = r'^bird:\s*(\d*).*left_x:\s*(\d*).*top_y:\s*(\d*).*width:\s*(\d*).*height:\s*(\d*).*$'
104
+
105
+ pat = re.compile(pattern, flags=re.MULTILINE)
106
+
107
+ data = []
108
+
109
+ for match in pat.finditer(text):
110
+
111
+ data.append({'bird':int(match.group(1)),
112
+
113
+ 'left_x':int(match.group(2)),
114
+
115
+ 'top_y':int(match.group(3)),
116
+
117
+ 'width':int(match.group(4)),
118
+
119
+ 'height':int(match.group(5))})
120
+
121
+ pprint(data)
122
+
123
+ #[{'bird': 30, 'height': 81, 'left_x': 877, 'top_y': 426, 'width': 157},
124
+
125
+ # {'bird': 27, 'height': 94, 'left_x': 874, 'top_y': 435, 'width': 158},
126
+
127
+ # {'bird': 30, 'height': 86, 'left_x': 877, 'top_y': 425, 'width': 153}]
128
+
129
+
130
+
131
+ # DataFrame化
132
+
133
+ df = pd.DataFrame(data)
134
+
135
+ print(df)
136
+
137
+ # bird left_x top_y width height
138
+
139
+ #0 30 877 426 157 81
140
+
141
+ #1 27 874 435 158 94
142
+
143
+ #2 30 877 425 153 86
144
+
145
+
146
+
147
+ # 以下を追加
148
+
149
+ # 再度ループを回してObjects:行をカウント
150
+
151
+ count = 0
152
+
153
+ frame_number = []
154
+
155
+ for line in text.split():
156
+
157
+ if line.startswith('Objects:'):
158
+
159
+ count = count + 1
160
+
161
+ if line.startswith('bird:'):
162
+
163
+ frame_number.append(count)
164
+
165
+ df['frame_number'] = frame_number
166
+
167
+
168
+
169
+ print(df)
170
+
171
+ # bird left_x top_y width height frame_number
172
+
173
+ #0 30 877 426 157 81 2
174
+
175
+ #1 27 874 435 158 94 2
176
+
177
+ #2 30 877 425 153 86 3
178
+
179
+
180
+
181
+ # csvに書き出す
182
+
183
+ df.to_csv('output.csv')
184
+
185
+ ```