系统要求我根据旧数据生成一个新变量。基本上,我要问的是,我是从原始值中随机抽取值(通过使用random
函数),并且其观察值至少是旧值的10倍,然后将其保存为新变量。
这是我的数据集:https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv
我要使用的变量是area
这是我的尝试,但给我一个module object is not callable
错误:
import pandas as pd
import random as rand
dataFrame = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv")
area = dataFrame['area']
random_area = rand(area)
print(random_area)
答案 0 :(得分:1)
您可以将sample
函数与replace=True
一起使用:
df = df.sample(n=len(df) * 10, replace=True)
或者,要仅对区域列进行采样,请使用
area = df.area.sample(n=len(df) * 10, replace=True)
另一个选项涉及np.random.choice
,看起来像这样:
df = df.iloc[np.random.choice(len(df), len(df) * 10)]
想法是从0-{len(df)-1
生成随机索引。第一个参数指定上限,第二个参数(len(df) * 10
)指定要生成的索引数。然后,我们使用生成的索引来索引df
。
如果您只想获取area
,就足够了。
area = df.iloc[np.random.choice(len(df), len(df) * 10), df.columns.get_loc('area')]
Index.get_loc
将{area}标签转换为iloc
的位置。
df = pd.DataFrame({'A': list('aab'), 'B': list('123')})
df
A B
0 a 1
1 a 2
2 b 3
# Sample 3 times the original size
df.sample(n=len(df) * 3, replace=True)
A B
2 b 3
1 a 2
1 a 2
2 b 3
1 a 2
0 a 1
0 a 1
2 b 3
2 b 3
df.iloc[np.random.choice(len(df), len(df) * 3)]
A B
0 a 1
1 a 2
1 a 2
0 a 1
2 b 3
0 a 1
0 a 1
0 a 1
2 b 3