Pythonでfor文の結果をデータフレームや辞書に格納する方法を以下に示します。
■辞書に格納する方法python
results = {}
for horse in horses:
profit = (unit_cost * buy[horse] * odds[horse] - total_buy).value()
results[str(horse)] = {
'buy_amount': buy[horse].value(),
'profit': profit
}
■データフレームに格納する方法python
import pandas as pd
data = []
for horse in horses:
profit = (unit_cost * buy[horse] * odds[horse] - total_buy).value()
data.append({
'horse': str(horse),
'buy_amount': buy[horse].value(),
'profit': profit
})
df = pd.DataFrame(data)
■リスト内包表記を使った簡潔な方法python
import pandas as pd
df = pd.DataFrame([
{
'horse': str(horse),
'buy_amount': buy[horse].value(),
'profit': (unit_cost * buy[horse] * odds[horse] - total_buy).value()
}
for horse in horses
])df.to_csv('result.csv')
データフレームの場合、で保存したり、print(df)で表形式で表示できます。