Ho 3 diversi dataframes che voglio unire, usando label e window come chiavi.
DataFrame1
Window Label FeatA
123 1 h
123 2 f
DataFrame2
Window Label FeatB
123 1 d
123 2 s
DataFrame3
Window Label FeatC
123 1 d
123 2 c
Risultato
Window Label FeatA FeatB FeatC
123 1 h d d
123 2 f s c
So come unire i dataframes usando pandas.concat
ma non so come specificare le chiavi. Qualsiasi aiuto sarebbe molto apprezzato.
risposte:
2 per risposta № 1Una pura risposta ai panda usando pd.concat
pd.concat([df.set_index(["Window", "Label"]) for df in [df1_, df2_, df3_]],
axis=1).reset_index()
3 per risposta № 2
Devi usare il merge
funzione per unire le tabelle, per il tuo caso, dato che hai più frame di dati da unire, puoi metterli in un elenco e poi usare il reduce
a partire dal functools
per unirli uno per uno:
import pandas as pd
from functools import reduce
reduce(lambda x, y: pd.merge(x, y, on = ["Window", "Label"]), [df1, df2, df3])
# Window Label FeatA FeatB FeatC
# 0 123 1 h d d
# 1 123 2 f s c
1 per risposta № 3
Puoi usare combine_first:
In[44]:df.combine_first(df1).combine_first(df2)[["Window","Label","FeatA","FeatB","FeatC"]]
Out[44]:
Window Label FeatA FeatB FeatC
0 123 1 h d d
1 123 2 f s c
o puoi usare fondersi:
In[30]:df.merge(df1,on=["Window","Label"]).merge(df2,on=["Window","Label"])
Out[30]:
Window Label FeatA FeatB FeatC
0 123 1 h d d
1 123 2 f s c