teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

.

2019/11/18 02:41

投稿

tachikoma
tachikoma

スコア3601

answer CHANGED
@@ -33,12 +33,29 @@
33
33
 
34
34
  for line in f.readlines():
35
35
  nSkiprow += 1
36
- if not line.startswith("データ"):
36
+ if line.startswith("データ"):
37
- continue
38
- else:
39
37
  break
40
38
 
41
39
  # 上で求めた行数をスキップしてread_tableで読み込む
42
- f = io.StringIO(s
40
+ f = io.StringIO(s)
43
41
  df = pandas.read_table(f, skiprows=nSkiprow)
42
+ ```
43
+
44
+ ----
45
+
46
+ StringIOを省くとこうなります。
47
+
48
+ ```python
49
+ filename = "text.TXT"
50
+
51
+ # "データ"までの行数をカウント
52
+ with open(filename) as f:
53
+ nSkiprow = 0
54
+ for line in f.readlines():
55
+ nSkiprow += 1
56
+ if line.startswith("データ"):
57
+ break
58
+
59
+ # 上で求めた行数をスキップしてread_tableで読み込む
60
+ df = pandas.read_table(filename, skiprows=nSkiprow)
44
61
  ```

1

2019/11/18 02:41

投稿

tachikoma
tachikoma

スコア3601

answer CHANGED
@@ -1,3 +1,44 @@
1
1
  スキップする行数がわかっていれば`skiprows`で最初の何行かを無視してやるのはどうでしょうか。
2
2
 
3
- [https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_table.html](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_table.html)
3
+ [https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_table.html](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_table.html)
4
+
5
+
6
+ ----
7
+
8
+ 下記のioモジュールはファイルオープンなどに適宜読み替えてください。
9
+
10
+ ```python
11
+ import io
12
+ import pandas
13
+
14
+ s = """サンプル: A
15
+ ファイル名: B
16
+ オペレータ: C
17
+
18
+ ピーク No. ピーク (nm) 高さ (%)
19
+ 1      1000   90
20
+ 2      2000   80
21
+ 3      3000   70
22
+
23
+ データ
24
+ nm %
25
+ 0 95
26
+ 100 94
27
+ 200 93"""
28
+
29
+ f = io.StringIO(s) # ファイルオープンと思ってください
30
+
31
+ # データをまでの行数をカウントする
32
+ nSkiprow = 0
33
+
34
+ for line in f.readlines():
35
+ nSkiprow += 1
36
+ if not line.startswith("データ"):
37
+ continue
38
+ else:
39
+ break
40
+
41
+ # 上で求めた行数をスキップしてread_tableで読み込む
42
+ f = io.StringIO(s
43
+ df = pandas.read_table(f, skiprows=nSkiprow)
44
+ ```