Python 以相同的方式对两个数据帧进行采样
我在做一个机器学习计算,有两个数据帧——一个是因子,另一个是目标值。我必须将培训和测试分为两部分。在我看来,我已经找到了方法,但我正在寻找更优雅的解决方案。这是我的密码:Python 以相同的方式对两个数据帧进行采样,python,pandas,Python,Pandas,我在做一个机器学习计算,有两个数据帧——一个是因子,另一个是目标值。我必须将培训和测试分为两部分。在我看来,我已经找到了方法,但我正在寻找更优雅的解决方案。这是我的密码: import pandas as pd import numpy as np import random df_source = pd.DataFrame(np.random.randn(5,2),index = range(0,10,2), columns=list('AB')) df_target = pd.DataFr
import pandas as pd
import numpy as np
import random
df_source = pd.DataFrame(np.random.randn(5,2),index = range(0,10,2), columns=list('AB'))
df_target = pd.DataFrame(np.random.randn(5,2),index = range(0,10,2), columns=list('CD'))
rows = np.asarray(random.sample(range(0, len(df_source)), 2))
df_source_train = df_source.iloc[rows]
df_source_test = df_source[~df_source.index.isin(df_source_train.index)]
df_target_train = df_target.iloc[rows]
df_target_test = df_target[~df_target.index.isin(df_target_train.index)]
print('rows')
print(rows)
print('source')
print(df_source)
print('source train')
print(df_source_train)
print('source_test')
print(df_source_test)
----已编辑-由unutbu提供的解决方案(midified)---
如果将
行
设置为长度为len(df)
的布尔数组,则可以使用df[rows]
获取True
行,使用df[~rows]
获取False
行:
import pandas as pd
import numpy as np
import random
np.random.seed(2013)
df_source = pd.DataFrame(
np.random.randn(5, 2), index=range(0, 10, 2), columns=list('AB'))
rows = np.random.randint(2, size=len(df_source)).astype('bool')
df_source_train = df_source[rows]
df_source_test = df_source[~rows]
print(rows)
# [ True True False True False]
# if for some reason you need the index values of where `rows` is True
print(np.where(rows))
# (array([0, 1, 3]),)
print(df_source)
# A B
# 0 0.279545 0.107474
# 2 0.651458 -1.516999
# 4 -1.320541 0.679631
# 6 0.833612 0.492572
# 8 1.555721 1.741279
print(df_source_train)
# A B
# 0 0.279545 0.107474
# 2 0.651458 -1.516999
# 6 0.833612 0.492572
print(df_source_test)
# A B
# 4 -1.320541 0.679631
# 8 1.555721 1.741279
下面你可以找到我的解决方案,它不涉及任何额外的变量
.sample
方法获取数据样本.index
方法获取索引slice()
ingX_sample = X.sample(10)
y_sample = y[X_sample.index]
我喜欢Alexander的答案,但我会在采样前添加一个索引重置。完整代码:
#索引重置
X.重置索引(就地=真,下降=真)
y、 重置索引(就地=真,下降=真)
#取样
X_样本=X.样本(10)
y_sample=y[X_sample.index]
重置索引用于匹配时没有问题。我认为更简单的解决方案是:
from sklearn.model_selection import train_test_split
df_source_train, df_source_test, df_target_train, df_target_test = train_test_split(df_source, df_target, train_size=.6)
塔克斯!因为我必须使用一些百分比,所以我修改了以rows=…开始的行。在这种情况下,您可以使用
rows=np.random.binomian(1,percentile*100,size=len(df_source))
。或者更确切地说,rows=np.random.binomian(1,percentile*100,size=len(df_source)).astype('bool')
非常好的解决方案,但过度依赖默认值(“显式优于隐式”)。因此,我在sample
中添加显式replace=False
,以确保避免数据泄漏。如果没有显式loc
(`y.loc[X_sample.index,:]),它将无法工作(默认轴在此处更改,轴1现在是默认的:)。
from sklearn.model_selection import train_test_split
df_source_train, df_source_test, df_target_train, df_target_test = train_test_split(df_source, df_target, train_size=.6)