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

时间:2020-06-04 21:59:56

标签: python pandas loc

我有一个如下数据集:

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

1 个答案:

答案 0 :(得分:2)

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

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