Pandas数据清理为文本值添加带有if-else语句的新列

2024-06-16 14:43:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的出版商名单:

+--------------+
|  Site Name   |
+--------------+
| Radium One   |
| Euronews     |
| EUROSPORT    |
| WIRED        |
| RadiumOne    |
| Eurosport FR |
| Wired US     |
| Eurosport    |
| EuroNews     |
| Wired        |
+--------------+

我想创建以下结果:

^{pr2}$

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

搜索前4个字符

如果文本。开始([Site Name],4)=“WIRE”然后“Wired”else

搜索最后3个字符

如果文本。结束([Site Name],3)=“一”,然后“RadiumOne”否则

如果找不到匹配项,则添加“Rest”

它不必区分大小写。在


Tags: name文本sitefronewired出版商名单
2条回答

我认为您可以使用双^{},并使用indexing with str创建条件:

s = df['Site Name'].str.lower()
df['new'] = np.where(s.str[:4] == 'wire', 'Wired', 
            np.where(s.str[-3:] == 'one', 'RadiumOne', 'Rest'))

但如果需要输出,还需要^{}和{a4}:

^{pr2}$

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

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)

相关问题 更多 >