簡體   English   中英

'>=' 在分段操作 'numpy.ndarray' 和 'str' 中不受支持

[英]'>=' not supported in piecewise operation 'numpy.ndarray' and 'str'

我有兩個數據框:

df_1 df_2

如果 df_2.date>=df_1.startDate 和 df_2.date,我正在嘗試從 df_2 中的 df_1 獲取“營地”

我試過分段操作:

condition = [(df_2.date.values >= start_date)&(df_2.date.values <= end_date) for start_date, end_date in zip(df_1.startDate.values, df_1.endDate.values)]
df_2['ID_matched'] = np.piecewise(np.zeros(len(sales)), condition, df_1.camp.values)

我收到此錯誤:

'>=' 在 'numpy.ndarray' 和 'str' 的實例之間不受支持

有沒有其他方法可以解決這個問題。 最終輸出應包含以下列:銷售、日期、營地

我可以得到這個解決方案的答案。

1. 從 df_1 創建一個具有唯一陣營名稱的列表,並將其轉換為以陣營為鍵和數字為元素的字典。

unique_campaign = list(set(df_1['camp'])) dictionary = dict(zip(df_1, list(range(1,len(unique_campaign)+1))))

2. 使用 applymap 將營地名稱轉換為字典中的數字。

df_1= df_1.applymap(lambda x: dictionary.get(x) if x in dictionary else x)

3. np.piecewise 操作

start_end_date = zip(df_1.startDate.values, df_1.endDate.values)

條件 = [(df_2.date.values >= start_date) & (df_2.date.values <= end_date) for start_date, end_date in start_end_date ]

df_2['camp'] = np.piecewise(np.zeros(len(df_2)), conditions,df_1.camp.values).astype(int)

4. 通過第 3 步,我們得到了 int 形式的答案。 現在我們映射字典中的整數以獲取營地名稱。

inv_dictionary = {values: 鍵的鍵,dictionary.items()} 中的值

df_2['camp'] = df_2['camp'].apply(lambda x: inv_dictionary.get(x) 如果 x 在 inv_dictionary else x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM