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

2024-09-24 00:23:45 发布

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

我有如下数据集:

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

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

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

Tags: 数据方法comidhttpurldfexample
1条回答
网友
1楼 · 发布于 2024-09-24 00:23:45

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

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

相关问题 更多 >