首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫-数据清理-为文本值添加带有if text语句的新列

熊猫-数据清理-为文本值添加带有if text语句的新列
EN

Stack Overflow用户
提问于 2016-11-01 11:56:35
回答 2查看 772关注 0票数 1

我有一个出版商的列表,如下所示:

代码语言:javascript
复制
+--------------+
|  Site Name   |
+--------------+
| Radium One   |
| Euronews     |
| EUROSPORT    |
| WIRED        |
| RadiumOne    |
| Eurosport FR |
| Wired US     |
| Eurosport    |
| EuroNews     |
| Wired        |
+--------------+

我想创建以下结果:

代码语言:javascript
复制
+--------------+----------------+
|  Site Name   | Publisher Name |
+--------------+----------------+
| Radium One   | RadiumOne      |
| Euronews     | Euronews       |
| EUROSPORT    | Eurosport      |
| WIRED        | Wired          |
| RadiumOne    | RadiumOne      |
| Eurosport FR | Eurosport      |
| Wired US     | Wired          |
| Eurosport    | Eurosport      |
| EuroNews     | Euronews       |
| Wired        | Wired          |
+--------------+----------------+

我想了解如何复制在Power Query中使用的代码:

搜索前4个字符

如果Text.Start(站点名称,4)=“连线”,则“连线”

搜索最后3个字符

如果Text.End(站点名,3)= "One“,则"RadiumOne”否则

如果没有找到匹配项,则添加"Rest“。

它不一定要区分大小写。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-11-01 13:00:42

我认为您可以使用双numpy.where和用用str索引创建的条件。

代码语言:javascript
复制
s = df['Site Name'].str.lower()
df['new'] = np.where(s.str[:4] == 'wire', 'Wired', 
            np.where(s.str[-3:] == 'one', 'RadiumOne', 'Rest'))

但是如果需要输出,也需要splittitle

代码语言:javascript
复制
df['new1'] = np.where(s.str[:4] == 'wire', 'Wired', 
             np.where(s.str[-3:] == 'one', 'RadiumOne', s.str.split().str[0].str.title()))

print (df)
      Site Name        new       new1
0    Radium One  RadiumOne  RadiumOne
1      Euronews       Rest   Euronews
2     EUROSPORT       Rest  Eurosport
3         WIRED      Wired      Wired
4     RadiumOne  RadiumOne  RadiumOne
5  Eurosport FR       Rest  Eurosport
6      Wired US      Wired      Wired
7     Eurosport       Rest  Eurosport
8      EuroNews       Rest   Euronews
9         Wired      Wired      Wired
票数 0
EN

Stack Overflow用户

发布于 2016-11-01 12:01:34

您可以使用apply方法和函数,如:

代码语言:javascript
复制
def handle_text(txt):
    if txt.lower()[:4] == 'wire':
        return 'Wired'
    elif txt.lower()[-3:] == 'one':
        return 'RadiumOne'
    return 'Rest'

df['Publisher Name'] = df['Site Name'].apply(handle_text)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40359568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档