Python:ufunc 'add' 不包含具有签名匹配类型的循环 dtype ('S21' ) dtype ('S21' ) dtype ('S21' )

标签 python pandas numpy dataframe concatenation

我有两个数据框,它们都有一个 Order ID 和一个 date

我想在第一个数据帧 df1 中添加一个标志:如果具有相同 order iddate 的记录在数据帧 df2,然后添加一个Y:

[ df1['R'] = np.where(orders['key'].isin(df2['key']), 'Y', 0)]

为此,我打算创建一个键,它将是 order_iddate 的串联,但是当我尝试以下代码时:

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/

相关文章:

Python:如何用 NaN 替换数组中的值?

python - 装饰器调用实例方法

python - 根据上一行添加新行

python - 在 Python 中管理连接创建?

python - Matplotlib - 在子图之间共享轴时缺少一些刻度

python - 使用pandas读取rpt文件

python - 在 numpy 数组 Python 中提取列的特定范围

python - 大于阈值的元素的 numpy.argmin

python - def some_method(param : int) syntax?) 有什么意义

python - 如何使用 Django 1.10 将数据从 html 表单存储到 postgres 数据库?