【发布时间】:2018-04-15 00:31:03
【问题描述】:
我将给出我尝试合并/转置的两个数据帧 Search_Exits 和 Page_Exits 以及我正在使用的代码的最小样本。
Search_Exits
Search_Term No._of_Searches_before %_Search_Exits_before
hello 10 .070
goodbye 100 .030
Page_Exits
Search_Term Exit_Pages_actual Ratios
hello /store/car 0.30
hello /store/b2b 0.30
hello /store/catalog/product/12 0.40
goodbye /store/car 1.00
我想在这里看到的结果是:
Search_Term No._of_Searches_before %_Search_Exits_before /store/car /store/catalog/product12 /store/catalog/product23 /store/b2b
hello 10 .070 0.30 0.40 0.00 0.30
goodbye 100 .030 1.00 0.00 0.00 0.00
我已经尝试了这个 stackoverflow 问题的答案中给出的所有 3 个版本:How to merge two tables and transpose rows to columns,但得到了所有这些版本的相同错误消息,我尝试了以下操作:
version 1
df = Search_Exits.merge(Page_Exits.groupby('Search_Term')['Exit_Pages_actual'].apply(lambda x: x.reset_index(drop=True)).unstack().reset_index())
version 2
Search_Exits.merge(Page_Exits.pivot_table(index='Search_Term', values='Ratios',columns='Exit_Pages_actual' + Page_Exits.groupby(['Search_Term'])['Exit_Pages_actual'].cumcount().astype(str)).reset_index())
version 3
(Search_Exits.set_index('Search_Term').join(Page_Exits.groupby('Search_Term')['Ratios'].apply(lambda x: x.tolist()).apply(pd.Series)).reset_index())
这三个都给我以下错误,所以我不知道该怎么办,如果有人可以帮忙:
TypeError: '>' not supported between instances of 'int' and
'datetime.datetime'
更新:
所以我尝试在我自己创建的模拟数据集上做同样的事情,但我不再收到错误消息(所以我想我不知道是什么导致了数据中的问题)但是我有两件事目前的发生方式与我希望它们发生的方式不同。首先,新生成的列没有被标记为我希望它们被标记为的相应“Exit_Pages_actual”。其次,每一列并不代表应该只归因于那个特定的“Exit_Pages_actual”的比率,所以我想知道我应该如何处理代码来改变它,让它像我想要的那样工作?目前,对于我的新数据集,其余部分大致如下:
Search_Term No._of_Searches_before %_Search_Exits_before 0 1 2 3
hello 10 .07 0.3 0.3 0.4 NaN
goodbye 100 .03 NaN 1.0 NaN
NaN
【问题讨论】:
-
嗯,似乎有一些日期时间列,但示例中没有...
-
对,我不知道为什么?有一列包含日期,但我从数据框中删除了它,所以我不确定问题是什么?
-
@mkheifetz 你做了
df = df.drop('DateCol', 1)吗?随着重新分配。 -
或
df.drop('DateCol', axis=1, inplace=True)没有分配;) -
但是请先检查您的示例数据是否返回错误,因为很难模拟它;)谢谢。
标签: python python-3.x pandas datetime transpose