Comparar dois DataFrames e mostrar a diferença está gerando um erro
Consigo encontrar a diferença comparando os dois DataFrames e concatenando as diferenças em um novo DataFrame, mas há um problema quando valores estão ausentes em um dos DataFrames, um erro é gerado:ValueError: Can only compare identically-labeled Series objects
Eu acho que há um problema com o índice do cabeçalho. Se você pode me ajudar, será ótimo.
df1 have one missing value at column 1980
df1
Country 1980 1981 1982 1983 1984
Bermuda 0.00687 0.00727 0.00971 0.00752
Canada 9.6947 9.58952 9.20637 9.18989 9.78546
Greenland 7 0.00746 0.00722 0.00505 0.00799
Mexico 3.72819 4.11969 4.33477 4.06414 4.18464
df2
Country 1980 1981 1982 1983 1984
Bermuda 0.77777 0.00687 0.00727 0.00971 0.00752
Canada 9.6947 9.58952 9.20637 9.18989 9.78546
Greenland 0.00791 0.00746 0.00722 0.00505 0.00799
Mexico 3.72819 4.11969 4.33477 4.06414 4.18464
def process_df(df):
res = df.set_index('Country').stack()
res.index.rename('Column', level=1, inplace=True)
return res
df1 = process_df(df1)
df2 = process_df(df2)
mask = (df1 != df2) & ~(df1.isnull() & df2.isnull())
df3 = pd.concat([df1[mask], df2[mask]], axis=1).rename({0:'From', 1:'To'}, axis=1)
print(df3)
Quero mostrar os valores ausentes como espaço em branco, exemplo abaixo:
From To
Country Column
Bermuda 1980 0.77777
Greenland 1980 0.00791 7
Lembre-se de que o código funciona bem se não houver valores ausentes, mas eu quero poder manipular e valores ausentes. Obrigado