替换熊猫列中的多个值而无循环

时间:2018-09-03 11:13:23

标签: python pandas dictionary

我有Pandas数据框,并想在df的特定列上替换很多值。

如何实现下面的无循环代码?

for i in range(len(data.loc[:, 'CityID'])):
    if data.loc[:, 'CityID'][i] == 1:
        data.loc[:, 'CityID'][i] = 1
    elif data.loc[:, 'CityID'][i] in (2, 3, 4, 21):
        data.loc[:, 'CityID'][i] = 2
    elif data.loc[:, 'CityID'][i] in (33, 34):
        data.loc[:, 'CityID'][i] = 4
    else:
        data.loc[:, 'CityID'][i] = 3

2 个答案:

答案 0 :(得分:4)

使用:

(document).on('click', '.genbutt', function() {
    var $row = jQuery(this).closest('tr');
    var $columns = $row.find('td');

    $columns.addClass('row-highlight');
    var values = "";
    var arrVal = [];
    jQuery.each($columns, function(i, item) {
        values = values + item.innerHTML + " ";
        arrVal = values.split(" ");


    });

    alert(GetUserName());

});

function GetUserName() {
    var userid = _spPageContextInfo.userId;
    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
    var requestHeaders = {
        "accept": "application/json;odata=verbose"
    };
    $.ajax({
        url: requestUri,
        contentType: "application/json;odata=verbose",
        headers: requestHeaders,
        success: onSuccess,
        error: onError
    });

    function onSuccess(data, request) {
        var loginName = data.d.Title;
        var emailName = _spPageContextInfo.userLoginName;
        return loginName;

    }

    function onError(error) {
        alert("error");
    }
}

答案 1 :(得分:4)

您可以将字典与pd.Series.map一起使用:

d = {1: 1, 2: 2, 3: 2, 4: 2, 21: 2, 33: 4, 34: 4}

data['CityID'] = data['CityID'].map(d).fillna(3)

如果词典结构很麻烦,则可以使用解压:

d = {1: 1, **dict.fromkeys((2, 3, 4, 21), 2), **dict.fromkeys((33, 34), 4}