我有如下数据集:
ID Type
1 a
2 a
3 b
4 b
5 c我正在尝试创建列URL,如所示,方法是根据"Type“并附加"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'])发布于 2020-06-04 22:02:35
您应该稍微修改一下命令:
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=5https://stackoverflow.com/questions/62204867
复制相似问题