我有两个dataframes:如何从熊猫数据框中排除值?
1)CUSTOMER_ID,性别 2)CUSTOMER_ID,... [其他字段]
的第一数据集是否为一答复的数据集(性别是一个答案)。因此,我想从第二个数据集中排除那些位于第一个数据集(我们知道的性别)中的customer_id并称之为“train”。其余记录应该成为'测试'数据集。
我有两个dataframes:如何从熊猫数据框中排除值?
1)CUSTOMER_ID,性别 2)CUSTOMER_ID,... [其他字段]
的第一数据集是否为一答复的数据集(性别是一个答案)。因此,我想从第二个数据集中排除那些位于第一个数据集(我们知道的性别)中的customer_id并称之为“train”。其余记录应该成为'测试'数据集。
我想你需要boolean indexing
和条件与isin
,反相boolean Series
由~
:
df1 = pd.DataFrame({'customer_id':[1,2,3],
'gender':['m','f','m']})
print (df1)
customer_id gender
0 1 m
1 2 f
2 3 m
df2 = pd.DataFrame({'customer_id':[1,7,5],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df2)
B C D E F customer_id
0 4 7 1 5 7 1
1 5 8 3 3 4 7
2 6 9 5 6 3 5
mask = df2.customer_id.isin(df1.customer_id)
print (mask)
0 True
1 False
2 False
Name: customer_id, dtype: bool
print (~mask)
0 False
1 True
2 True
Name: customer_id, dtype: bool
train = df2[mask]
print (train)
B C D E F customer_id
0 4 7 1 5 7 1
test = df2[~mask]
print (test)
B C D E F customer_id
1 5 8 3 3 4 7
2 6 9 5 6 3 5
它的工作原理。现在我已经训练了没有性别列的数据框。并且想要连接这两个数据集。例如,在训练数据集中,我有多个具有相同customer_id的行。我想为每个customer_id添加适当的性别值。 –
你需要['merge'](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html) - 'df3 = pd.merge(train,df1,on ='customer_id ')'? – jezrael
是的,非常感谢。 –
对不起你以后'火车= DF2 [DF2 [ 'CUSTOMER_ID'] ISIN(〜。 DF1 [ 'CUSTOMER_ID'])]'? – EdChum