在python中收集计算结果并将其转换为数据帧进行分析的有效方法是什么



我正在使用循环对数据集进行一些计算。然后,基于随机事件,我将计算一些浮点数(这意味着我事先不知道要检索多少浮点(。我想把这些数字(结果(保存在某种列表中,然后把它们保存到数据帧列中(我想在循环中的每次迭代中都有这些结果,并把它们保存在一列中,这样我就可以比较它们,这意味着每次迭代都会产生一个结果的"列表",这些结果将被注册在df列中(

示例:

for y in range(1,10):
for x in range(1,100):
if(x>random number and x<y):
result=2*x

我想通过组合x,y将所有结果保存在数据帧列中。例如,列中x=1,y=2的结果,然后列中x=2,y=2。。。等等,结果不一样,所以我想我会用fillna。

现在我知道我可以创建一个带有最大索引的空数据帧,然后逐个结果填充它,但我认为有更好的方法!提前谢谢。

您希望利用numpypandas提供的效率。如果使用numpy.where,则可以在if语句为False时将值设置为nan,否则可以执行公式:

import numpy as np
import pandas as pd
np.random.seed(0) # so you can reproduce my result, you can remove this in practice
x = list(range(10))
y = list(range(1, 11))
random_nums = 10 * np.random.random(10)
df = pd.DataFrame({'x' : x, 'y': y})
# the first argument is your if condition
df['new_col'] = np.where((df['x'] > random_nums) & (df['x'] < df['y']), 2*df['x'], np.nan)
print(df)

这里,random_nums生成要与之进行比较的随机数的整个np.ndarray。这提供

x   y  new_col
0  0   1      NaN
1  1   2      NaN
2  2   3      NaN
3  3   4      NaN
4  4   5      NaN
5  5   6      NaN
6  6   7     12.0
7  7   8      NaN
8  8   9      NaN
9  9  10     18.0

如果您的公式(此处为2*x(计算速度相对较快,则速度尤其快。

最新更新