首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫根据其他栏目的条件和价值创建新栏目

问熊猫根据其他栏目的条件和价值创建新栏目
EN

Stack Overflow用户
提问于 2020-06-04 21:59:56
回答 1查看 117关注 0票数 1

我有如下数据集:

代码语言:javascript
复制
ID Type
1   a  
2   a  
3   b  
4   b 
5   c

我正在尝试创建列URL,如所示,方法是根据"Type“并附加"ID”指定一个不同的URL。

代码语言:javascript
复制
ID Type URL
1   a  http://example.com/examplea/id=1
2   a  http://example.com/examplea/id=2
3   b  http://example.com/bbb/id=3
4   b  http://example.com/bbb/id=4
5   c  http://example.com/testc/id=5

我在代码中使用了类似的东西,但它不是只为该行提取ID,而是在附加具有Type = a的所有ID。

代码语言:javascript
复制
df.loc[df['Type'] == 'a', 'URL']= 'http://example.com/examplea/id='+str(df['ID'])
df.loc[df['Type'] == 'b', 'URL']= 'http://example.com/bbb/id='+str(df['ID'])
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-04 22:02:35

您应该稍微修改一下命令:

代码语言:javascript
复制
df.loc[df['Type'] == 'a', 'URL']= 'http://example.com/examplea/id='+df['ID'].astype(str)
df.loc[df['Type'] == 'b', 'URL']= 'http://example.com/bbb/id='+df['ID'].astype(str)

或者您可以像这样使用map:

代码语言:javascript
复制
url_dict = {
    'a':'http://example.com/examplea/id=',
    'b':'http://example.com/bbb/id=',
    'c':'http://example.com/testc/id='
}

df['URL'] = df['Type'].map(url_dict) + df['ID'].astype(str)

输出:

代码语言:javascript
复制
   ID Type                               URL
0   1    a  http://example.com/examplea/id=1
1   2    a  http://example.com/examplea/id=2
2   3    b       http://example.com/bbb/id=3
3   4    b       http://example.com/bbb/id=4
4   5    c     http://example.com/testc/id=5
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62204867

复制
相关文章

相似问题

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