我正在尋找基于 Python 的解決方案來解決我經常遇到的常見任務。
(我知道,這肯定有很酷的 SQL 魔法,但是……不是現在。)
情況是:給定一個表,如果相同
,我們要更改欄位。
(假設總是包含或為空 if is )f2oidf2baroid42
| ID | f1 | f2 | 樣的 |
|---|---|---|---|
| 1 | 富 | 酒吧 | 42 |
| 2 | 富 | 49 | |
| 3 | 巴茲 | 42 |
變成:
| ID | f1 | f2 | 樣的 |
|---|---|---|---|
| 1 | 富 | 酒吧 | 42 |
| 2 | 富 | 49 | |
| 3 | 巴茲 | 酒吧 | 42 |
我目前正在使用itertools.combinations以避免重復比較。
這似乎比雙 for 回圈更有效。
但是對于非常大的資料集,它仍然變得不方便......考慮到 Big-O-Notation。
我的問題是:可以通過pandas或numpy更優雅地解決問題嗎?
uj5u.com熱心網友回復:
假設 f2 總是包含 bar 或者如果 oid 為 42 則為空
也許我們也可以使用groupby 變換first:
df['f2'] = df.replace('', np.nan).groupby('oid')['f2'].transform('first').fillna('')
輸出:
id f1 f2 oid
0 1 foo bar 42
1 2 foo 49
2 3 baz bar 42
uj5u.com熱心網友回復:
我能想到的唯一解決方案是使用groupby ffill:
df['f2'] = df.replace('', np.nan).groupby('oid')['f2'].ffill()
輸出:
>>> df
id f1 f2 oid
0 1 foo bar 42
1 2 foo NaN 49
2 3 baz bar 42
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/448854.html
標籤:Python python-3.x 熊猫 数据框 麻木的
