'20/08/13更新:読みづらかったので、記事構成を編集しました。
下図のように、行方向にデータが並んでいるcsvファイルがあるとします。1列目はインデックス名、2列目以降は各行の数値データです。このデータをpandasで読み込んでリストに格納したり、別ファイル内の文字列と置換する雛形コードを載せました。

本コードの動作仕様について説明します。上記とは別のテキストファイルである下図左の「@TAGET@」の行を下図右のように書き換えます。

▼本プログラム
import os, sys, shutil
import pandas as pd
def my_extract_data(fname):
if os.path.isfile(fname):
df = pd.read_csv(fname, header=0)
df = df.set_index('name')
print(df)
indexlist=df.index.values.tolist()
print(indexlist)
buf=[]
for i in range(len(indexlist)):
tmplist=[]
tmplist=df.loc[str(indexlist[i])].values.tolist()
buf.append('func(name=' +str(indexlist[i]) + ',\n')
buf.append(' x_min='+str(tmplist[0])+ ', x_max=' +str(tmplist[1])+ ',\n')
buf.append(' y_min='+str(tmplist[2])+ ', y_max=' +str(tmplist[3])+ ',\n')
buf.append(' z_min='+str(tmplist[4])+ ', z_max=' +str(tmplist[5])+ ')\n')
else:
print("file not found")
return buf
def my_edit_file(target_file, target_sentence, replace_list):
if os.path.exists(target_file + ".backup"):
shutil.copy2(target_file + ".backup", target_file)
else:
shutil.copy2(target_file, target_file + ".backup")
with open(target_file + ".backup", "r") as f2:
with open(target_file, "w") as f1:
for row in f2:
if row.find(target_sentence) != -1:
f1.writelines(replace_list)
else:
f1.write(row)
if __name__ == "__main__":
in_file = 'data.csv'
target_file = 'target.txt'
target_sentence = '@TARGET@'
replace_list = my_extract_data(in_file)
my_edit_file(target_file, target_sentence, replace_list)
上記コード中の特記事項(備忘録)は次の1~4です。
1. インデックス位置を指定する方法
①列番号で指定する場合:例えば、index_col=0と指定すると一番左の列がインデックス名となります。
df = pd.read_csv('ファイル.csv', index_col=0)
②列名で指定する場合:一旦ファイルを読み込んだ後に、set_indexで指定します。
df = pd.read_csv('ファイル.csv', header=0)
df = df.set_index('列名')
2. 指定行のデータをリストとして取得する方法
tmplist=df.loc['インデックス名'].values.tolist()
3. 指定文字列による条件分岐の方法
if row.find('指定文字列') != -1:
4. ファイルへ書き出し方法
①リストで書き込みする場合:writelines() 要素毎に改行したい場合には、+' \n'と改行コードを入れる必要あり。
②文字列で書き込む場合:wrtie()
以上
<広告>
リンク