熊猫根据其他列中的条件和值创建新列

用户3242036

我有一个类似以下的数据集:

ID Type
1   a  
2   a  
3   b  
4   b 
5   c

我试图通过基于“类型”指定其他URL并附加“ ID”来创建所示的列URL。

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。

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'])
广晃

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

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

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)

输出:

   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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章