![](/img/trans.png)
[英]What's the best way to replace NaN values (in a Pandas DataFrame) with values from a separate Pandas Series?
[英]What is the fastest way to perform a replace on a column of a Pandas DataFrame based on the index of a separate Series?
抱歉,如果我一直使用錯誤的關鍵字,但是我無法找到一種有效的方法來將DataFrame列中的整數的所有實例替換為第二系列中對應的索引值。
我正在使用第三方程序的輸出,該程序從輸入矩陣中剝離行和列標簽,並用其對應的索引替換它們。 我想從索引中還原真正的標簽。
我有一個有關數據框和序列的虛擬示例:
In [6]: df
Out[6]:
idxA idxB var2
0 0 1 2.0
1 0 2 3.0
2 2 4 2.0
3 2 1 1.0
In [8]: labels
Out[8]:
0 A
1 B
2 C
3 D
4 E
Name: label, dtype: object
目前,我正在將該系列轉換為字典,並使用replace
:
label_dict = labels.to_dict()
df['idxA'] = df.idxA.replace(label_dict)
df['idxB'] = df.idxB.replace(label_dict)
這確實給了我預期的結果:
In [12]: df
Out[12]:
idxA idxB var2
0 A B 2.0
1 A C 3.0
2 C E 2.0
3 C B 1.0
但是,這對於我的完整數據集來說非常慢(表中約380萬行,有19,000個標簽)。 有沒有更有效的方法來解決這個問題?
謝謝!
編輯:我接受@coldspeed的答案。 無法在評論答復中粘貼代碼塊,但他的解決方案將偽代碼加速了大約一個數量級:
In [10]: %timeit df.idxA.replace(label_dict)
4.41 ms ± 132 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [11]: %timeit df.idxA.map(labels)
435 µs ± 3.93 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
您可以使用apply
來為每一列調用map
:
df.loc[:, 'idxA':'idxB'] = df.loc[:, 'idxA':'idxB'].apply(lambda x: x.map(labels))
df
idxA idxB var2
0 A B 2.0
1 A C 3.0
2 C E 2.0
3 C B 1.0
這有效地遍歷了每一列(但是單列的map
操作是矢量化的,因此速度很快 )。 這樣做可能更快
cols_of_interest = ['idxA', 'idxB', ...]
for c in cols_of_interest: df[c] = df[c].map(labels)
map
比replace
快,這取決於要替換的列數。 你的旅費可能會改變。
df_ = df.copy()
df = pd.concat([df_] * 10000, ignore_index=True)
%timeit df.loc[:, 'idxA':'idxB'].replace(labels)
%%timeit
for c in ['idxA', 'idxB']:
df[c].map(labels)
6.55 ms ± 87.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.95 ms ± 70 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.