Amartin
Amartin

Reputation: 337

Create new dataframe column based on a specific character of a string in another column, pandas

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

Upvotes: 0

Views: 1161

Answers (2)

AMH
AMH

Reputation: 528

You can try this using numpy.

import numpy as np

DF["col2"] = np.where(DF["col1"].str[-1]=="g",1,0)

Upvotes: 1

Rakesh
Rakesh

Reputation: 82785

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

Upvotes: 1

Related Questions