擅长:python、mysql、java
<p>我将<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer">^{<cd1>}</a>与<a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#selection-by-callable" rel="nofollow noreferrer">^{<cd2>}</a>一起使用:</p>
<pre><code>cols = ['col1', 'col2', 'col3', 'col4']
df['b']=(df[cols].stack()
.loc[lambda x: x.str.contains('b')]
.reset_index(level=1,drop=1)
#.fillna('-') #for the expected output
)
</code></pre>
<p><strong>输出</strong></p>
<pre><code> ID col0 col1 col2 col3 col4 col5 b
0 1 jack a/h t/m w/n y/h 56 NaN
1 2 sam z/n b/w NaN NaN 93 b/w
2 3 john b/i y/d p/d NaN 33 b/i
</code></pre>