社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在Pandas Python中基于列文本创建列

hammeroflight • 6 年前 • 2486 次点击  

我有一个数据框(系列) 'df' 如下所示:

Name
A1001
A1002
B1001
C1001
A1003
B1002
B1003
C1002
D1001
D1002

我想创建一个名为Company的新专栏 'Alpha' 如果文本以 'A' , 'Bravo' 如果文本以 'B' 和 'Others' 如果文本以其他内容开头。

我试过:

df['Company'] = 'Alpha' if df.Name.str.startswith('A') else 'Other'

但它给了我一个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

预期产量:

Name     Company
A1001    Alpha
A1002    Alpha
B1001    Bravo
C1001    Other
A1003    Alpha
B1002    Bravo
B1003    Bravo
C1002    Other
D1001    Other
D1002    Other

怎么能做到?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52716
文章 [ 2 ]  |  最新文章 6 年前