python - 根据另一列的多个值创建新列
问题描述
我有一个数据框,其中一列中有这些值:
在:
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'
我尝试.str
在x
and之间添加contains
, like x.str.contains()
,但这也给出了错误。
我怎样才能做到这一点?
谢谢!
解决方案
怎么样:
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
推荐阅读
- cryptography - 在 github 上托管使用强密码学的开源软件项目是否存在法律问题?
- python - Python - InvalidRequestError:无法反映:请求的表在引擎中不可用(mysql + mysqlconnector://
- swift - 如何使用组合实现派生属性?
- android - Camera2:应在后台线程上调用 createCaptureRequest()
- php - 如何处理刀片 laravel
- java - 如何将登录状态存储在 sharedpreferences 中
- java - FOP 无法从 url 加载图像
- python - 如何正确使用 sklearn 的 cross_validate 和 One Hot Encoded 类?
- c++ - 通过元素原始位置的奇偶校验来稳定分区 std::vector
- xamarin.forms - 如何在 VS 2019 上混淆 xamarin 应用程序