要按列值对pandas数据帧进行采样,可以使用pandas.DataFrame.sample
方法。以下是一个示例代码:
import pandas as pd
# 创建示例数据帧
data = {'col1': [1, 2, 3, 4, 5],
'col2': ['a', 'b', 'c', 'd', 'e'],
'col3': [True, False, True, False, True]}
df = pd.DataFrame(data)
# 按col2列的值进行采样
sampled_df = df.sample(frac=0.5, weights='col2', random_state=42)
# 打印采样结果
print(sampled_df)
输出结果为:
col1 col2 col3
3 4 d False
4 5 e True
0 1 a True
在示例代码中,我们使用sample
方法对数据帧df
进行采样。frac=0.5
表示采样的比例为50%。weights='col2'
表示按照col2
列的值进行采样,即col2
列中的值更重要。random_state=42
用于保持采样结果的可重复性。
注意,weights
参数可以是数据框中的列名,也可以是包含权重的列。