首页 > 解决方案 > 根据另一列的多个值创建新列

问题描述

我有一个数据框,其中一列中有这些值:

在:

df.line.unique()

出去:

array(['Line71A', 'Line71B', 'Line75B', 'Line79A', 'Line79B', 'Line75A', 'Line74A', 'Line74B',
       'Line70A', 'Line70B', 'Line58B', 'Line70', 'Line71', 'Line74', 'Line75', 'Line79', 'Line58'],
      dtype=object)

我想根据值字符串是否包含 LineXX 创建一个具有 2 个值的新列,如下所示:

if (df.line.str.contains("Line70")  or (df.line.str.contains("Line71") or (df.line.str.contains("Line79")):
   return 1
else:
   return 0

所以新列中的值应该是1 box_type,如果其中的值df.line包含“Line70”、“Line71”、“Line79”,其余的应该是0

我尝试使用以下代码执行此操作:

df['box_type'] = df.line.apply(lambda x: 1 if x.contains('Line70') or x.contains('Line71') or x.contains('Line79') else 0)

但我得到这个错误:

AttributeError: 'str' object has no attribute 'contains'

我尝试.strxand之间添加contains, like x.str.contains(),但这也给出了错误。

我怎样才能做到这一点?

谢谢!

标签: pythonpandas

解决方案


怎么样:

df['box_type'] = df.line.str.contains('70|71|79')

样本数据:

np.random.seed(1)
df = pd.DataFrame({'line':np.random.choice(a, 10)})

输出:

      line  box_type
0  Line75A     False
1   Line70      True
2   Line71      True
3  Line70A      True
4  Line70B      True
5   Line70      True
6  Line75A     False
7   Line79      True
8  Line71A      True
9   Line58     False

推荐阅读