Pandas: Set variable to value in cell, if another cell on same row contains string
<p>Let's say my Pandas <code>DataFrame</code> contains the following:</p>

<pre><code>Row    Firstname    Middlename Lastname
â¦
10     Roy         G.          Biv
11     Cnyder      M.          Uk
12     Pan         T.          One
â¦
</code></pre>

<p>If a cell in <code>["Lastname"]</code> contains <code>"Biv"</code>, I would like to set the Python variable <code>first_name =</code> to <code>"Roy"</code>.</p>

<p>I've been away from Pandas for a while and am unsure on the right way to accomplish this. I've looked at ways to combine <code>df.iloc</code>/<code>df.loc</code> etc with <code>df.at/df.where</code> and <code>str.contains</code> but have to admit I'm kind of lost on the proper way to put the conditional together with setting the variable.</p>

<p>In (poor, <strong>incorrect</strong>) pseudo-code, I'm looking for:</p>

<p><code>first_name = df["Firstname"][np.where([df["Lastname"].str.contains("Biv") ...</code></p>

<p>If you want just the scalar value then you can access the first value in the result array and assign this:</p>

<pre><code>firstname = df.loc[df['Lastname'].str.contains('Biv'), 'Firstname'][0]
</code></pre>

<p>Note that really you should check if it's not empty though:</p>

<pre><code>if len(df.loc[df['Lastname'].str.contains('Biv'), 'Firstname']) &gt; 0:
    firstname = df.loc[df['Lastname'].str.contains('Biv'), 'Firstname'][0]
</code></pre>

python pandas