根据另一列中的字符串的特定字符pandas创建新的数据框列

时间:2020-06-10 12:21:47

标签: python pandas dataframe

我有一个带有包含字符串的列的数据框。我想知道是否有可能基于数据框创建一个新列。 这是该列的示例:

   col1
016e3d588c
071b4x718g
011e3d598c
041e0i608g

我想根据字符串的最后一个字符创建一个新列。这是我尝试过的:

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

我想要这样的新列:

col2
  0
  1
  0
  1

但是我的代码具有以下输出:

col2
  0
  0
  0
  0

有可能做到吗?

预先感谢

2 个答案:

答案 0 :(得分:1)

使用str.endswith()

例如:

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

输出:

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

答案 1 :(得分:1)

您可以使用numpy进行尝试。

import numpy as np

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