[英]Pandas Create New Column Based Off of Condition and Value in Other Column
I have a data set like the following:我有一个如下数据集:
ID Type
1 a
2 a
3 b
4 b
5 c
And I'm trying to create the column URL as shown by specifying a different URL based on the "Type" and appending the "ID".我正在尝试创建列 URL,如图所示,根据“类型”指定不同的 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
I'm using something like this for the code but it is not pulling in the ID for just that row, instead it is appending all the IDs that have Type = a.我在代码中使用了类似的东西,但它并没有为那一行提取 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'])
You should alter the command a bit:您应该稍微改变一下命令:
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)
Or you can use map
like this:或者您可以像这样使用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)
Output: Output:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.