本記事の特記事項はpandasのインデックスのデータ処理について下記2点です。
1. インデックス名(行名)を列名で指定して与える
下記例では、一行目に列名IDの列がインデックス(行名)になります。
df_s = df.set_index('ID')
2. インデックス(行名)のその行のデータをリストとして取得する
下記例では 、インデックス(行名)がAAAのその行名以外の行データをリスト化します。
mylist1 = df_s.loc['AAA'].values.tolist()
本プログラムの仕様を示す。下図のようなデータの並びの「book.csv」ファイルがある。ID名にAAAとBBBと呼ぶ二つがあり、それぞれx_min~z_maxまでデータが6つある。この計12個のデータを一旦、pandasのデータフレーム化する。そして、インデックス名(行名)をID名に変換した後に、ID名を指定することで数値データをリスト化する。

その後、そのリストデータを用いて、下図左のような別ファイル中の@で囲まれた箇所を下図右のように置換する。

本プログラムを実行すると下図に示すようにデータ処理の過程をprint出力する。図中の一番下にあるout_list をみると多重配列のようになっているが、各行の数値データをリスト化して、それらをタプルとしている。

▼本プログラム
import os, sys
import shutil
import pandas as pd
def extract_data(myFname1):
df = pd.read_csv(myFname1)
print(df)
df_s = df.set_index('ID')
print(df_s)
mylist1 = df_s.loc['AAA'].values.tolist()
print(mylist1)
mylist2 = df_s.loc['BBB'].values.tolist()
print(mylist2)
return mylist1, mylist2
def editFile(filepath, out_list):
if os.path.exists(filepath + ".backup"):pass
else:
shutil.copy2(filepath, filepath + ".backup")
with open(filepath + ".backup", "r") as f2:
with open(filepath, "w") as f1:
for row in f2:
temp = row.replace("@MY_NO01@", str(out_list[0][0])) \
.replace("@MY_NO02@", str(out_list[0][1])) \
.replace("@MY_NO03@", str(out_list[0][2])) \
.replace("@MY_NO04@", str(out_list[0][3])) \
.replace("@MY_NO05@", str(out_list[0][4])) \
.replace("@MY_NO06@", str(out_list[0][5])) \
.replace("@MY_NO07@", str(out_list[1][0])) \
.replace("@MY_NO08@", str(out_list[1][1])) \
.replace("@MY_NO09@", str(out_list[1][2])) \
.replace("@MY_NO10@", str(out_list[1][3])) \
.replace("@MY_NO11@", str(out_list[1][4])) \
.replace("@MY_NO12@", str(out_list[1][5]))
f1.write(temp)
def main():
out_list = extract_data(input_file)
print("out_list ->" + str(out_list))
editFile(filepath, out_list)
if __name__ == '__main__':
path = os.getcwd()
input_file = "book.csv"
target_file = "target.txt"
file_path = os.path.join(path, target_file)
main()
hk29.hatenablog.jp
以上
<広告>
リンク