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

回答編集履歴

5

コードを整理。(処理内容は同じ)

2025/08/27 07:53

投稿

melian
melian

スコア21428

answer CHANGED
@@ -1,14 +1,11 @@
1
- `numpy.genfromtxt()` で読み込んで、各ブロックの要素の順序を入れ替えます。なお、質問文に添付されている図の通りの順序だとすれば `blks[:, [2, 0, 1]]` になるので、その様にしています。
1
+ `numpy.genfromtxt()` で読み込んで、各ブロックの要素の順序を入れ替えます。なお、質問文に添付されている図の通りの順序だとすれば `blks[:, [2, 0, 1, 3]]` になるので、その様にしています。
2
2
  ```python
3
3
  import os
4
4
  import numpy as np
5
5
 
6
6
  data_files = ['sample20.txt']
7
7
  for f in data_files:
8
- blks = np.genfromtxt(f, dtype=str).reshape(-1, 4)
9
- print(f'blkold\n{blks}\n')
10
- blks[:, :3] = blks[:, [2, 0, 1]]
11
- print(f'blknew\n{blks}\n')
12
- newname = os.path.splitext(f)[0] + 'mod.txt'
8
+ np.savetxt(os.path.splitext(f)[0] + 'mod.txt',
9
+ np.genfromtxt(f, dtype=str).reshape(-1, 4)[:, [2, 0, 1, 3]],
13
- np.savetxt(newname, blks, delimiter='', fmt='%s\n')
10
+ delimiter='\n', fmt='%s', newline='\n\n')
14
11
  ```

4

numpy.savetxt() で delimiter を指定して、fmt を変更

2025/08/26 12:05

投稿

melian
melian

スコア21428

answer CHANGED
@@ -10,5 +10,5 @@
10
10
  blks[:, :3] = blks[:, [2, 0, 1]]
11
11
  print(f'blknew\n{blks}\n')
12
12
  newname = os.path.splitext(f)[0] + 'mod.txt'
13
- np.savetxt(newname, blks, fmt='%s\n%s\n%s\n%s\n')
13
+ np.savetxt(newname, blks, delimiter='', fmt='%s\n')
14
14
  ```

3

2025/08/26 11:46

投稿

melian
melian

スコア21428

answer CHANGED
@@ -1,4 +1,4 @@
1
- `numpy.loadtxt()` で読み込んで、各ブロックの要素の順序を入れ替えます。なお、質問文に添付されている図の通りの順序だとすれば `blks[:, [2, 0, 1]]` になるので、その様にしています。
1
+ `numpy.genfromtxt()` で読み込んで、各ブロックの要素の順序を入れ替えます。なお、質問文に添付されている図の通りの順序だとすれば `blks[:, [2, 0, 1]]` になるので、その様にしています。
2
2
  ```python
3
3
  import os
4
4
  import numpy as np

2

別回答の内容を参考にしてnumpy.loadtxt()からnumpy.genfromtxt()に変更。(データを全て文字列(str)として読み込む)

2025/08/26 11:45

投稿

melian
melian

スコア21428

answer CHANGED
@@ -4,12 +4,11 @@
4
4
  import numpy as np
5
5
 
6
6
  data_files = ['sample20.txt']
7
-
8
7
  for f in data_files:
9
- blks = np.loadtxt(f, dtype=int).reshape(-1, 4)
8
+ blks = np.genfromtxt(f, dtype=str).reshape(-1, 4)
10
9
  print(f'blkold\n{blks}\n')
11
10
  blks[:, :3] = blks[:, [2, 0, 1]]
12
11
  print(f'blknew\n{blks}\n')
13
12
  newname = os.path.splitext(f)[0] + 'mod.txt'
14
- np.savetxt(newname, blks, fmt='%d\n%d\n%d\n%d\n')
13
+ np.savetxt(newname, blks, fmt='%s\n%s\n%s\n%s\n')
15
14
  ```

1

2025/08/26 08:07

投稿

melian
melian

スコア21428

answer CHANGED
@@ -2,7 +2,6 @@
2
2
  ```python
3
3
  import os
4
4
  import numpy as np
5
- import pandas as pd
6
5
 
7
6
  data_files = ['sample20.txt']
8
7