python - Pandas 不同的采样大小
问题描述
有人可以帮我处理熊猫吗?
我有一组数据 n = 50,如果我需要根据不同的大小随机选择数据,我该如何从数据中选择随机样本。
例如:
- a = 从 50 开始,我需要选择 25
- b = 从 50 中,我需要选择 5
- c = Fom 50,我需要选择 10
- d = 从 50 开始,我需要选择 2
- e = 从 50 中,我需要选择 8
我用了
a = df.sample(25)
如果我创建 b=df.sample(5),我如何确定它与 a、c、d、e 不是同一个样本?
解决方案
import pandas as pd
import numpy as np
# Create DataFrame With Dummy Data
src_df = pd.DataFrame(np.linspace(150, 500, 50), columns=['Value'])
# Randomly Shuffle Data
shuffled = src_df.sample(frac=1)
# Number of Rows Per Group
rows_to_grab = [25, 5, 10, 2, 8]
# Make Sure Row Groups Add up to Total Number of Rows
assert sum(rows_to_grab) == len(shuffled)
dfs = []
start_index = 0
for rows in rows_to_grab:
# Append Shuffled Rows to dfs
dfs.append(shuffled.iloc[start_index: start_index + rows])
start_index += rows
# Print Out
for header, df in zip("abcde", dfs):
print(f' {header} ')
print(df)
也可以手动分配组:
a = shuffled.iloc[:25]
b = shuffled.iloc[25:30]
c = shuffled.iloc[30:40]
d = shuffled.iloc[40:42]
e = shuffled.iloc[42:50]
样本可能的输出e
:
e
Value
13 242.857143
48 492.857143
28 350.000000
25 328.571429
39 428.571429
17 271.428571
41 442.857143
18 278.571429
推荐阅读
- css - 图像高度作为父 div 高度
- python - 使用 MNE python 加载实地考察数据的问题
- android - 生成签名的 apk 时文件上传失败,但是当应用程序处于调试状态时,文件正在上传到服务器
- css - 如果没有足够的空间,如何使网格 minmax 转到 1 列?
- admin - Magento 2.0 中基于 Store 的限制
- asp.net-core - 如何检索参与多对多关系的对象?
- java - 在对外部服务进行 http 调用之前排队多个请求 - spring webflux 和 projectreactor
- javascript - 是否有任何方法可以仅“传播”在 React 组件中传递的合成事件?
- angular - 反转 Angular 组件的 HTML
- c++ - 如何访问 std::vector
在qml?