【发布时间】:2018-02-08 12:14:43
【问题描述】:
我正在 Python 中对我的数据进行一些 RFM 分析,并调整了 Joal Correia 的 github 代码(如下),该代码将结果输出到 CSV,还将结果添加到数据框,然后将其发布到 BigQuery 表。
它有效,但我缺少 BigQuery 中数据的第一列,即“客户”ID,这是我的结果中的唯一字符串。该列在 .csv 中,在 python 的数据框中,只是不在 BQ 结果中,谁能告诉我我在哪里丢失了这个?
注意:我已经删除了大部分 RFM 代码来整理这篇文章,下面的几行显示了我的补充。
更新:我运行了 print(results.keys()),但在此列表中没有看到“客户”,这与它在导出中不可见有关吗?
Index(['recency', 'frequency', 'monetary_value', 'R_Quartile', 'F_Quartile',
'M_Quartile', 'RFMClass'],
dtype='object')
https://github.com/joaolcorreia/RFM-analysis
import sys, getopt
import pandas as pd
from datetime import datetime
from google.cloud import bigquery
.....
rfmSegmentation['RFMClass'] = rfmSegmentation.R_Quartile.map(str) + rfmSegmentation.F_Quartile.map(str) + rfmSegmentation.M_Quartile.map(str)
# Output the results as a CSV
rfmSegmentation.to_csv(outputfile, sep=',')
# Once the CSV is generated we also drop the results into a DataFrame and output to BigQuery.
results = pd.DataFrame(rfmSegmentation)
print(results.head())
destination_table = 'xxx.RFM'
project_id = 'xxx'
results.to_gbq(destination_table, project_id, chunksize=10000, verbose=True, reauth=False, if_exists='replace', private_key='xxx.json')
print (" ")
print (" DONE! Check %s" % (outputfile))
print (" ")
以下是我的脚本在 CSV 中的结果,在 BigQuery 中存在“客户”,在下方,列不存在:
【问题讨论】:
-
@sgDysregulation 你指的是哪个模式?如果您指的是 BigQuery,则“客户”不会出现在架构中。
-
根据我对
pandas的理解,我猜rfmSegmentation已经是一个pandas Dataframe了,否则你将无法使用to_csv()方法。在这种情况下,为什么要再次将其转换为 DataFrame (results = pd.DataFrame(rfmSegmentation))?我认为这不会影响,但我认为这也没有必要。回到主要问题,如果 customer 列未显示在键列表中,这是一个很好的指示或错误可能在哪里。print(results.head())的结果是哪个,是否显示 customer 列? -
此外,您是否也可以打印来自
rfmSegmentation的keys,例如print(rfmSegmentation.keys())?结果是什么。它应该包含 customer 键,因为输出的 CSV 文件确实包含该列。 -
嗨@dsesto 感谢您的回复,我设法解决了这个问题,“客户”列被用作索引,但未发送到 BigQuery。我用范围值替换了索引,然后根据需要将客户字段导出到数据中。听起来您的建议会产生同样的效果!
-
很高兴我能提供帮助,并且您能够解决您的问题!
标签: python pandas google-bigquery