[英]Is there a way of using isin() as calculator function for another column in pandas dataframe?
I have a column as 'PRODUCT_ID' in my pandas dataframe.我的熊猫数据框中有一列为“PRODUCT_ID”。 I want to create a calculated column based on this column that PRODUCT_IDs in [3, 5, 8] will be taking value 'old' and others 'new'.
我想基于此列创建一个计算列,其中 [3、5、8] 中的 PRODUCT_ID 将取值“旧”而其他值“新”。
Right now I'm using a for loop to check every single index of the dataframe.现在我正在使用 for 循环来检查数据帧的每个索引。
portfoy['PRODUCT_TYPE'] = np.nan
for ind in portfoy.index:
if portfoy.loc[ind, 'PRODUCT_CODE'] in [3, 5, 8]:
portfoy.loc[ind, 'PRODUCT_TYPE'] = 'old'
else:
portfoy.loc[ind, 'PRODUCT_TYPE'] = 'new'
This code seems to take a lot of time.这段代码似乎需要很多时间。 Is there a better way to do this?
有一个更好的方法吗?
My data looks like:我的数据看起来像:
CUSTOMER![]() |
PRODUCT_ID ![]() |
other columns![]() |
---|---|---|
2345 ![]() |
3 ![]() |
------------- ![]() |
3456 ![]() |
5 ![]() |
------------- ![]() |
2786 ![]() |
5 ![]() |
------------- ![]() |
使用numpy.where
和Series.isin
进行矢量化快速解决方案:
portfoy['PRODUCT_TYPE'] = np.where(portfoy['PRODUCT_CODE'].isin([3, 5, 8]), 'old', 'new')
you can use masks to conditional update the data frame您可以使用掩码有条件地更新数据框
portfoy.loc[portfoy.PRODUCT_CODE.isin([3,5,8]),'PRODUCT_TYPE'] = 'old'
portfoy.loc[~portfoy.PRODUCT_CODE.isin([3,5,8]),'PRODUCT_TYPE'] = 'new'
portfoy.PRODUCT_CODE.isin([3,5,8] is the mask portfoy.PRODUCT_CODE.isin([3,5,8] 是掩码
~ is the negation of the mask ~ 是掩码的否定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.