我有一个出版商的列表,如下所示:
+--------------+
| Site Name |
+--------------+
| Radium One |
| Euronews |
| EUROSPORT |
| WIRED |
| RadiumOne |
| Eurosport FR |
| Wired US |
| Eurosport |
| EuroNews |
| Wired |
+--------------+我想创建以下结果:
+--------------+----------------+
| 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“。
它不一定要区分大小写。
发布于 2016-11-01 13:00:42
我认为您可以使用双numpy.where和用用str索引创建的条件。
s = df['Site Name'].str.lower()
df['new'] = np.where(s.str[:4] == 'wire', 'Wired',
np.where(s.str[-3:] == 'one', 'RadiumOne', 'Rest'))但是如果需要输出,也需要split和title。
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发布于 2016-11-01 12:01:34
您可以使用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)https://stackoverflow.com/questions/40359568
复制相似问题