Python 如何从另一个数据帧中的一个数据帧中查找相同的列?
我有一个这样的数据帧Python 如何从另一个数据帧中的一个数据帧中查找相同的列?,python,pandas,numpy,dataframe,merge,Python,Pandas,Numpy,Dataframe,Merge,我有一个这样的数据帧 tabla_aciertos= {'Numeros_acertados' : [5,5,5,4,4,3,4,2,3,3,1,2,2],'Estrellas_acertadas': [2,1,0,2,1,2,0,2,1,0,2,1,0]} categorias = [1,2,3,4,5,6,7,8,9,10,11,12,13] categoria_de_premios = pd.DataFrame (tabla_aciertos,index = [categorias] )
tabla_aciertos= {'Numeros_acertados' : [5,5,5,4,4,3,4,2,3,3,1,2,2],'Estrellas_acertadas': [2,1,0,2,1,2,0,2,1,0,2,1,0]}
categorias = [1,2,3,4,5,6,7,8,9,10,11,12,13]
categoria_de_premios = pd.DataFrame (tabla_aciertos,index = [categorias] )
categoria_de_premios
另一个df:
sorteos_anteriores.iloc[:,:]
uno dos tres cuatro cinco Estrella1 Estrella2 bolas_Acertadas estrellas_Acertadas
Fecha
2020-10-13 5 14 38 41 46 1 10 0 1
2020-09-10 11 15 35 41 50 5 8 1 0
2020-06-10 4 21 36 41 47 9 11 0 0
2020-02-10 6 12 15 40 45 3 9 0 0
2020-09-29 4 14 16 41 44 11 12 0 1
... ... ... ... ... ... ... ... ... ...
2004-12-03 15 24 28 44 47 4 5 0 0
2004-05-03 4 7 33 37 39 1 5 0 1
2004-02-27 14 18 19 31 37 4 5 0 0
2004-02-20 7 13 39 47 50 2 5 1 0
2004-02-13 16 29 32 36 41 7 9 0 0
1363 rows × 9 columns
现在我需要看到在df的每一行中,“sorteos_anteriores”位于第一个df的所有行中的一行中,“tabla_aciertos”
我举个例子,
在“sorteos_anteriores”中的发动机中,您有:
2019-11-2在“bolas_Acertadas”=5和“estrellas_Acertadas=1”列中
。现在您转到第一张表“tabla_acertos”,在(index 2=“Numeros_acertados”=5和Estrellas_acertadas=1)
。你获得了二等奖(指数=2)。您应该在“sorteos_anteriores”中创建一个新列“Prize”,如果您有某种奖品0或Nan(如果没有),则在每行中写一个从1到13的数字
我尝试过:
sorteos_anteriores ['categorias'] = sorteos_anteriores(sorteos_anteriores.loc[:,'bolas_Acertadas':'estrellas_Acertadas'] == tabla_premios.iloc[ : ,0:2])
还有where和merge,但都不起作用
谢谢你的帮助
多亏了Cuina Max,我才能做到。
为什么合并不起作用?使用how=outer
应该可以工作,用NAs填充与categoria\u de\u premios
不匹配的行。如果索引未按数字排序,您可以使用.index
将索引转换为列。是的,@Ehsan,您完全正确。它也更简单。我已经更新了答案,谢谢。它起作用了。虽然我唯一改变的是内心的感受。谢谢
sorteos_anteriores ['categorias'] = sorteos_anteriores(sorteos_anteriores.loc[:,'bolas_Acertadas':'estrellas_Acertadas'] == tabla_premios.iloc[ : ,0:2])
# supposing that the indexes, starting from one, correspond to the the premiums
categoria_de_premios['Categoria'] = df.index
# Merge using pd.merge and the appropriate arguments
sorteos_anteriores = (sorteos_anteriores.merge(
categoria_de_premios,
how='outer',
left_on=['bolas_Acertadas','estrellas_Acertadas'],
right_on=['Numeros_acertados', 'Estrellas_acertadas']
)).drop(columns=['Numeros_acertados', 'Estrellas_acertadas'])