我有两个数据框,它们都有一个 Order ID
和一个 date
。
我想在第一个数据帧 df1
中添加一个标志:如果具有相同 order id
和 date
的记录在数据帧 df2
,然后添加一个Y
:
[ df1['R'] = np.where(orders['key'].isin(df2['key']), 'Y', 0)]
为此,我打算创建一个键,它将是 order_id
和 date
的串联,但是当我尝试以下代码时:
df1['key']=df1['Order_ID']+'_'+df1['Date']
我收到这个错误
ufunc 'add' did not contain a loop with signature matching types dtype('S21') dtype('S21') dtype('S21')
df1 看起来像这样:
Date | Order_ID | other data points ...
201751 4395674 ...
201762 3487535 ...
这些是数据类型:
df1.info()
RangeIndex: 157443 entries, 0 to 157442
Data columns (total 6 columns):
Order_ID 157429 non-null object
Date 157443 non-null int64
...
dtypes: float64(2), int64(2), object(2)
memory usage: 7.2+ MB
df1['Order_ID'].values
array(['782833030', '782834969', '782836416', ..., '783678018',
'783679806', '783679874'], dtype=object)
最佳答案
问题是您不能将对象数组(包含字符串)添加到数字数组,这只是模棱两可:
>>> import pandas as pd
>>> pd.Series(['abc', 'def']) + pd.Series([1, 2])
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21')
您需要明确地将您的Dates
转换为str
。
我不知道如何在 pandas 中有效地做到这一点,但你可以使用:
df1['key'] = df1['Order_ID'] + '_' + df1['Date'].apply(str) # .apply(str) is new
关于Python:ufunc 'add' 不包含具有签名匹配类型的循环 dtype ('S21' ) dtype ('S21' ) dtype ('S21' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44527956/