0

I have a dataframe with a column that contain strings. I want to know if it is possible to create a new column based on the dataframe. This is an example of the column:

   col1
016e3d588c
071b4x718g
011e3d598c
041e0i608g

I want to create a new column based on the last character of the string. This is what I tried:

for i in DF['col1']:
    if i[-1] == 'g':
        DF['col2'] = 1
    else:
        DF['col2'] = 0

I want the new column like this:

col2
  0
  1
  0
  1

but my code have the following output:

col2
  0
  0
  0
  0

Is possible to do it?

Thanks in advance

2 Answers 2

1

You can try this using numpy.

import numpy as np

DF["col2"] = np.where(DF["col1"].str[-1]=="g",1,0)
Sign up to request clarification or add additional context in comments.

Comments

1

Using str.endswith()

Ex:

df = pd.DataFrame({"Col1": ['016e3d588c', '071b4x718g', '011e3d598c', '041e0i608g']})
df["Col2"] = df["Col1"].str.endswith("g").astype(int)
print(df)

Output:

         Col1  Col2
0  016e3d588c     0
1  071b4x718g     1
2  011e3d598c     0
3  041e0i608g     1

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.