![](/img/trans.png)
[英]Most efficient way to compare two panda data frame and update one dataframe based on condition
[英]Compare panda data frame indices and update the rows
我有兩個 excel 文件,由 pandas 讀取。 我正在將文件 1 中的索引與文件 2 中的索引(長度不同(例如:10,100)進行比較,如果它們匹配,則第二個文件中的 row[index] 將為零,否則不會改變。我正在使用for 和 if 循環,但是我想處理的數據越多(1e3,5e3),運行時間就會變長。那么,有沒有更好的方法來進行這種比較?這是我正在使用的一個例子。
df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
index=[4, 5, 6], columns=['A', 'B', 'C'])
df1 = pd.DataFrame([['w'], ['y' ], ['z']],
index=[4, 5, 1])
for j in df1.index:
for i in df.index:
if i == j:
df.loc[i, :] = 0
else:
df.loc[i, :] = df.loc[i, :]
print(df)
這里不需要循環,您可以通過DataFrame.mask
和Series.isin
將每行的值設置為0
(必須將index
轉換為Series
以避免ValueError: Array conditional must be same shape as self
):
df = df.mask(df.index.to_series().isin(df1.index), 0)
或者使用Index.isin
和numpy.where
如果想提高性能:
arr = np.where(df.index.isin(df1.index)[:, None], 0, df)
df = pd.DataFrame(arr, index=df.index, columns=df.columns)
print(df)
A B C
4 0 0 0
5 0 0 0
6 10 20 30
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.