擅长:python、mysql、java
<p>您可以尝试对特定的“SUB”列组行使用<code>df.pivot</code>,后跟.ffill()、bfill()。你知道吗</p>
<pre><code>df1 = df.pivot(columns='0')
df1.columns = df1.columns.map(lambda x: x[1])
df1.SUB = df1.SUB.ffill()
df1.groupby('SUB').ffill().groupby('SUB').bfill().drop_duplicates()
#5.89 ms ± 1.84 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
# as time constraints, without use of lambda operation
#df1.groupby(df1.SUB.ffill()).apply(lambda x: x.ffill().bfill()).drop_duplicates()
#16 ms ± 1.06 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>输出:</p>
<pre><code> SUB CAT CODE CODE1 SUB
2 123 SKU 1000123 NaN 123
3 123 SKU 1000234 NaN 123
6 456 LIQ NaN 1000345 456
7 456 LIQ NaN 1000534 456
8 456 LIQ NaN 1000433 456
</code></pre>