简体   繁体   中英

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

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

You can try this using numpy .

import numpy as np

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM