【问题标题】:Pandas Create New Column Based Off of Condition and Value in Other ColumnPandas 根据其他列中的条件和值创建新列
【发布时间】:2020-09-24 01:00:30
【问题描述】:

我有如下数据集:

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

【问题讨论】:

    标签: python pandas pandas-loc


    【解决方案1】:

    你应该稍微改变一下命令:

    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
    

    【讨论】:

    • 谢谢!我选择了第一个,因为我必须在最后附加一些额外的字符串。
    猜你喜欢
    • 2020-04-25
    • 2020-05-30
    • 1970-01-01
    • 2017-08-26
    • 2020-06-02
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多