Python Pandas 更新数据框并计数更新的单元格数量

4 投票
1 回答
1027 浏览
提问于 2025-04-18 02:55

假设我正在用另一个数据表(df2)来更新我的数据表。

import pandas as pd
import numpy as np

df=pd.DataFrame({'axis1': ['Unix','Window','Apple','Linux'],
                 'A': [1,np.nan,1,1],
                 'B': [1,np.nan,np.nan,1],
                 'C': [np.nan,1,np.nan,1],
                 'D': [1,np.nan,1,np.nan],
                 }).set_index(['axis1'])

print (df)

df2=pd.DataFrame({'axis1': ['Unix','Window','Apple','Linux','A'],
                 'A': [1,1,np.nan,np.nan,np.nan],
                 'E': [1,np.nan,1,1,1],
                 }).set_index(['axis1'])

df = df.reindex(columns=df2.columns.union(df.columns),
                index=df2.index.union(df.index))

df.update(df2)

print (df)

有没有什么命令可以让我知道更新了多少个单元格?(从Nan变成了1)我想用这个来跟踪我的数据表的变化。

1 个回答

0

在pandas中,我想不出有什么内置的方法可以直接做到这一点。你需要在更新之前先保存原始的数据框(df),然后再进行比较。关键是要确保在比较时,NaN(缺失值)和非零值的处理方式是一样的。这里的df3是更新之前的df的一个副本:

In [104]:

df.update(df2)
df
Out[104]:
         A   B   C   D   E
axis1                     
A      NaN NaN NaN NaN   1
Apple    1 NaN NaN   1   1
Linux    1   1   1 NaN   1
Unix     1   1 NaN   1   1
Window   1 NaN   1 NaN NaN

[5 rows x 5 columns]
In [105]:

df3
Out[105]:
         A   B   C   D   E
axis1                     
A      NaN NaN NaN NaN NaN
Apple    1 NaN NaN   1 NaN
Linux    1   1   1 NaN NaN
Unix     1   1 NaN   1 NaN
Window NaN NaN   1 NaN NaN

[5 rows x 5 columns]
In [106]:

# compare but notice that NaN comparison returns True
df!=df3
Out[106]:
            A      B      C      D     E
axis1                                   
A        True   True   True   True  True
Apple   False   True   True  False  True
Linux   False  False  False   True  True
Unix    False  False   True  False  True
Window   True   True  False   True  True

[5 rows x 5 columns]

In [107]:
# use numpy count_non_zero for easy counting, note this gives wrong result
np.count_nonzero(df!=df3)
Out[107]:
16

In [132]:

~((df == df3) | (np.isnan(df) & np.isnan(df3)))
Out[132]:
            A      B      C      D      E
axis1                                    
A       False  False  False  False   True
Apple   False  False  False  False   True
Linux   False  False  False  False   True
Unix    False  False  False  False   True
Window   True  False  False  False  False

[5 rows x 5 columns]
In [133]:

np.count_nonzero(~((df == df3) | (np.isnan(df) & np.isnan(df3))))
Out[133]:
5

撰写回答