因此,我尝试将特定值(“财产损失”)与数据集中的每一行相关联,但是我对此遇到了一些麻烦。具体来说,如果要满足for循环中指定的条件(例如,如果i> = 0.8062,打印等),我想将“ MD”列中每一行的值乘以一个数字(0.02、0.15等)。 。我在下面包含了我的代码:
df['RAND'] = np.random.uniform(0, 1, size=df.index.size)
dfRAND = list(df['RAND'])
def sim_1():
for i in dfRAND:
result = []
if i >= 0.8062:
df['Property Damage'] = df['MD'].apply(lambda x: x * 0.02)
print(list(val for x, val in enumerate(df['Count']) if
x == dfRAND.index(i)), 'LF0', i,':', df['Property Damage'])
elif 0.01 <= i < 0.89062:
df['Property Damage'] = list(df['MD'].apply(lambda x: x * 0.15))
print(list(val for x, val in enumerate(df['Count']) if
x == dfRAND.index(i)),'LF1', i, ':', df['Property Damage'])
elif 0.05 <= i < 0.01:
df['Property Damage'] = list(df['MD'].apply(lambda x: x * 0.20))
print(list(val for x, val in enumerate(df['Count']) if
x == dfRAND.index(i)),'LF2', i,':', df['Property Damage'])
elif 0.025 <= i < 0.05:
df['Property Damage'] = list(df['MD'].apply(lambda x: x * 0.50))
print(list(val for x, val in enumerate(df['Count']) if
x == dfRAND.index(i)),'LF3', i,':', df['Property Damage'])
elif 0.0125 <= i < 0.025:
df['Property Damage'] = list(df['MD'].apply(lambda x: x * 1))
print(list(val for x, val in enumerate(df['Count']) if
x == dfRAND.index(i)),'LF4', i,':', df['Property Damage'])
elif 0.0063 <= i < 0.0125:
df['Property Damage'] = list(df['MD'].apply(lambda x: x * 1))
print(list(val for x, val in enumerate(df['Count']) if
x == dfRAND.index(i)),'LF5', i,':', df['Property Damage'])
我目前遇到的问题是代码为每一行打印了所有“财产损失”值。我希望它为我提供基于for循环中满足任何条件的特定行的“财产损失”值。
感谢您的帮助。预先感谢。
答案 0 :(得分:1)
您是否正在寻找类似的东西?
my_bins = {pd.Series.max(df['RAND'])-1: 1,
.01: .15,
.0125: 1,
.025: .5,
.05: .2,
pd.Series.max(df['RAND'])+1 : .02}
df['rand_multiplier'] = pd.cut(df['RAND'], bins = sorted(my_bins.keys()), labels = list(range(len(my_bins) - 1))).apply(lambda x: my_bins[sorted(my_bins.keys())[x]])
df.apply(lambda row: row['MD'] * row['rand_multiplier'], axis = 1)
我有点着急,所以这不是最漂亮的东西。基本上,我根据您拥有的条件创建了bin,并创建了一个“乘数”列,该列将df['RAND']
中的每个条目与一个乘数相关联。然后,我们可以遍历df并将乘数应用于您的“ MD”行。
当然,没有'MD'数据,我无法显示产生的结果。