【发布时间】:2019-03-01 17:08:03
【问题描述】:
我一直在努力创建一个蒙特卡罗模拟,该模拟将遍历我的数据框的每个 ID,并产生它们各自的均值和标准偏差。我已经能够编写代码来获取任何一个 ID,但不能遍历我的数据框中的整个 ID 列表。所以我可以单独编写每一行,但我需要代码来遍历任何可变的 ID 列表。
在这里,我尝试创建一个列表列表,其中可以存储每组 Monte Carlo 观测值(并且可以从中获取平均值和标准差)。我不相信这将是最有效的编码方式,但这是我目前所知道的。无论如何要在每个 ID 上运行 Monte Carlo 模拟(没有专门调用每个 ID)?我需要能够从列表中添加和删除各种 ID 和相应的数据。
这是对以下内容的跟进:Utilizing Monte Carlo to Predict Revenue in Python
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
ID = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Revenue = [1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800, 1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800]
odds = [0.5, 0.6, 0.33, 0.1, 0.9, 0.87, 0.37, 0.55, 0.97, 0.09, 0.5, 0.6, 0.33, 0.1, 0.9, 0.87, 0.37, 0.55, 0.97, 0.09]
d = {'ID': ID, 'Revenue': Revenue, 'Odds': odds}
df = pd.DataFrame(d)
df['Expected Value'] = df['Revenue']*df['Odds']
print(df)
num_samples = 100
df['Random Number'] = np.random.rand(len(df))
def monte_carlo_array(df):
for _ in range(len(df)):
yield []
mc_arrays = list(monte_carlo_array(df))
# Fill each list with 100 observations (no filtering necessary)
id_1 = []
filter_1 = (df['ID'] == 5)
for _ in range(num_samples):
sample = df['Revenue'] * np.where(np.random.rand(len(df)) < \
df['Odds'], 1, 0)
for l in monte_carlo_array(df):
for i in l:
mc_arrays[i].append(sample.sum())
id_1.append(sample.loc[filter_1].sum())
# Plot simulation results.
n_bins = 10
plt.hist([id_1], bins=n_bins, label=["ID: 1"])
plt.legend()
plt.title("{} simulations of revenue".format(num_samples))
print(mc_arrays)
df['Monte Carlo Mean'] = np.mean(mc_arrays[0])
print(df['Monte Carlo Mean'])
【问题讨论】:
标签: python python-3.x pandas montecarlo