0
    Col1    Col2
0    APT     UB0
1    AK0     UUP
2    IL2     PB2
3    OIU     U5B
4    K29     AAA  

My data frame looks similar to the above data. I'm trying to change the values in Col1 if the corresponding values in Col2 have the letter "B" in it. If the value in Col2 has "B", then I want to add "-B" to the end of the value in Col1.

Ultimately I want Col1 to look like this:

       Col1
0     APT-B
1       AK0
2     IL2-B
..      ...

I have an idea of how to approach it... but I'm somewhat confused because I know my code is incorrect. In addition there are NaN values in my actual code for Col1... which will definitely give an error when I'm trying to do val += "-B" since it's not possible to add a string and a float.

for value in dataframe['Col2']:
    if "Z" in value:
        for val in dataframe['Col1']:
            val += "-B"

Does anyone know how to fix/solve this?

3 Answers 3

3

Rather than using a loop, lets use pandas directly:

import pandas as pd

df = pd.DataFrame({'Col1': ['APT', 'AK0', 'IL2', 'OIU', 'K29'], 'Col2': ['UB0', 'UUP', 'PB2', 'U5B', 'AAA']})
df.loc[df.Col2.str.contains('B'), 'Col1'] += '-B'

print(df)

Output:

Col1 Col2
0  APT-B  UB0
1    AK0  UUP
2  IL2-B  PB2
3  OIU-B  U5B
4    K29  AAA
Sign up to request clarification or add additional context in comments.

Comments

0

You have too many "for" loops in your code. You just need to iterate over the rows once, and for any row satisfying your condition you make the change.

for idx, row in df.iterrows():
    if 'B' in row['Col2']:
        df.loc[idx, 'Col1'] = str(df.loc[idx, 'Col1']) + '-B'

edit: I used str to convert the previous value in Col1 to a string before appending, since you said you sometimes have non-string values there. If this doesn't work for you, please post your test data and results.

Comments

0

You can use a lambda expression. If 'B' is in Col2, then '-B' get appended to Col1. The end result is assigned back to Col1.

df['Col1'] = df.apply(lambda x: x.Col1 + ('-B' if 'B' in x.Col2 else ''), axis=1)
>>> df
    Col1 Col2
0  APT-B  UB0
1    AK0  UUP
2  IL2-B  PB2
3  OIU-B  U5B
4    K29  AAA

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.