Py学习  »  Python

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

hammeroflight • 5 年前 • 1798 次点击  

我有一个数据框(系列) '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
 
1798 次点击  
文章 [ 2 ]  |  最新文章 5 年前
jezrael
Reply   •   1 楼
jezrael    5 年前

使用 numpy.select 具有 Series.str.startswith :

df['Company'] = np.select([df.Name.str.startswith('A'), 
                           df.Name.str.startswith('B')], 
                           ['Alpha', 'Bravo'], 
                           default='Other')
print (df)
    Name Company
0  A1001   Alpha
1  A1002   Alpha
2  B1001   Bravo
3  C1001   Other
4  A1003   Alpha
5  B1002   Bravo
6  B1003   Bravo
7  C1002   Other
8  D1001   Other
9  D1002   Other
Erfan
Reply   •   2 楼
Erfan    5 年前

使用 np.select 要创建多条件列:

letter = df['Name'].str[0]
df['Company'] = np.select([letter.eq('A'), letter.eq('B')], ['Alpha', 'Bravo'], default='Other')

    Name Company
0  A1001   Alpha
1  A1002   Alpha
2  B1001   Bravo
3  C1001   Other
4  A1003   Alpha
5  B1002   Bravo
6  B1003   Bravo
7  C1002   Other
8  D1001   Other
9  D1002   Other

同样的方法,但现在我们使用一个更“自我解释”的代码:

letter = df['Name'].str[0]
conditions = [letter.eq('A'), letter.eq('B')]
choices = ['Alpha', 'Bravo']

df['Company'] = np.select(conditions, choices, default='Other')