大熊猫中的if-else条件赋值

时间:2018-04-10 20:54:17

标签: python pandas ternary-operator

我想根据已存在的列的值为列分配值。此代码有效,但我希望不使用assignapply非就地执行此操作。

如果可以一步完成,也可以避免从intfloat的隐式转换。

我使用assign包含了我的尝试,ValueError提出import pandas as pd original = pd.DataFrame({'col': ['a', 'b', 'c']}) d = original.copy() d.loc[d.col.isin(['b', 'x']), 'new'] = 1 d.loc[~d.col.isin(['b', 'x']), 'new'] = 99 d # : col new # : 0 a 99.0 # : 1 b 1.0 # : 2 c 99.0 # original.assign(new=lambda x: (1 if x.col.isin(['b', 'x']) else 99)) # ValueError

 public static async Task Upload(string project_uid, string filename, Stream payload)
 {
     var api = PlanGridClient.Create(Properties.Settings.Default.ApiKey);

     var versionRequest = new UploadVersionRequest
     {
         NumberOfFiles = 1,
         VersionName = "MyVersion"  // how does this get used??
     };

     var versionUpload = await api.UploadVersion(project_uid, versionRequest);

     foreach (var fileUploadRequest in versionUpload.FileUploadRequests)
     {
         var uploadFile = new UploadFile
         {
             FileName = filename
         };

         var fileUpload = await api.UploadFileToVersion(project_uid, versionUpload.Uid, fileUploadRequest.Uid, uploadFile);

         await api.Upload<object>(fileUpload, payload);
     }

     await api.CompleteVersionUpload(project_uid, versionUpload.Uid);
}

1 个答案:

答案 0 :(得分:3)

您可以使用numpy.where():

import numpy as np
original["new"] = np.where(original["col"].isin(["b", "x"]), 1, 99)
print(original)
#  col  new
#0   a   99
#1   b    1
#2   c   99