熊猫:无需循环即可获得数据子集

时间:2018-05-09 17:25:10

标签: python pandas machine-learning

我试图根据customer_id将列车数据拆分为训练/测试拆分(数据框中的多行可以有相同的customer_id),我想我们能做build df_testdrop from df_train部分没有大熊猫本地方式的循环?

#Split data for train / test split

df_train = pd.read_csv('data/train.csv')
print('df_train.shape', df_train.shape)

df_train = df_train.replace(np.nan, 'nan', regex=True)

train_customer_id_set = df_train.customer_id.unique()
print('len(train_customer_id_set)', len(train_customer_id_set))

#Split train data to train/test by customer_id
n = 1000
test_customer_id_set = list(train_customer_id_set)
random.shuffle(test_customer_id_set)
test_customer_id_set = test_customer_id_set[:n]

#Q: how to do it without cycle?

#build df_test
df_list = []
for customer_id in test_customer_id_set:
    df = df_train[df_train['customer_id']==customer_id]
    df_list.append(df)
df_test = pd.concat(df_list)

#drop from df_train
for customer_id in test_customer_id_set:
    df_train = df_train.drop(df_train[df_train.customer_id==customer_id].index)

train_customer_id_set = df_train.customer_id.unique()

print('df_train.shape', df_train.shape)
print('df_test.shape', df_test.shape)

1 个答案:

答案 0 :(得分:2)

按照您计算test_customer_id_set的点,看起来您正在做的事情相当于:

df_test = df_train[df_train.customer_id.isin(test_customer_id_set)]
df_train = df_train[~df_train.customer_id.isin(test_customer_id_set)]