【发布时间】:2020-06-24 03:33:00
【问题描述】:
对于给定的数据框如下:
id|address|sell_price|market_price|status|start_date|end_date
1|7552 Atlantic Lane|1170787.3|1463484.12|finished|2019/8/2|2019/10/1
1|7552 Atlantic Lane|1137782.02|1422227.52|finished|2019/8/2|2019/10/1
2|888 Foster Street|1066708.28|1333385.35|finished|2019/8/2|2019/10/1
2|888 Foster Street|1871757.05|1416757.05|finished|2019/10/14|2019/10/15
2|888 Foster Street|NaN|763744.52|current|2019/10/12|2019/10/13
3|5 Pawnee Avenue|NaN|928366.2|current|2019/10/10|2019/10/11
3|5 Pawnee Avenue|NaN|2025924.16|current|2019/10/10|2019/10/11
3|5 Pawnee Avenue|Nan|4000000|forward|2019/10/9|2019/10/10
3|5 Pawnee Avenue|2236138.9|1788938.9|finished|2019/10/8|2019/10/9
4|916 W. Mill Pond St.|2811026.73|1992026.73|finished|2019/9/30|2019/10/1
4|916 W. Mill Pond St.|13664803.02|10914803.02|finished|2019/9/30|2019/10/1
4|916 W. Mill Pond St.|3234636.64|1956636.64|finished|2019/9/30|2019/10/1
5|68 Henry Drive|2699959.92|NaN|failed|2019/10/8|2019/10/9
5|68 Henry Drive|5830725.66|NaN|failed|2019/10/8|2019/10/9
5|68 Henry Drive|2668401.36|1903401.36|finished|2019/12/8|2019/12/9
#copy above data and run below code to reproduce dataframe
df = pd.read_clipboard(sep='|')
我想将id 和address 分组,并根据以下条件计算mean_ratio 和result_count:
-
mean_ratio: 是 groupbyid和address并计算满足以下条件的行的平均值:statusisfinishedandstart_dateis in the range of2019-09and2019-10 -
result_count:是groupbyid和address,计算行数满足以下条件:status要么是finished要么是failed,而start_date在2019-09和@987654343的范围内@
所需的输出将如下所示:
id address mean_ratio result_count
0 1 7552 Atlantic Lane NaN 0
1 2 888 Foster Street 1.32 1
2 3 5 Pawnee Avenue 1.25 1
3 4 916 W. Mill Pond St. 1.44 3
4 5 68 Henry Drive NaN 2
到目前为止我已经尝试过:
# convert date
df[['start_date', 'end_date']] = df[['start_date', 'end_date']].apply(lambda x: pd.to_datetime(x, format = '%Y/%m/%d'))
# calculate ratio
df['ratio'] = round(df['sell_price']/df['market_price'], 2)
为了过滤start_date在2019-09和2019-10的范围内:
L = [pd.Period('2019-09'), pd.Period('2019-10')]
c = ['start_date']
df = df[np.logical_or.reduce([df[x].dt.to_period('m').isin(L) for x in c])]
要过滤行状态为finished 或failed,我使用:
mask = df['status'].str.contains('finished|failed')
df[mask]
但我不知道如何使用这些来获得最终结果。提前感谢您的帮助。
【问题讨论】:
-
抱歉,我用 excel 创建了数据框,然后使用了
pd.read_clipboard(),我不知道如何将其转换为代码。 -
我已经编辑了数据,不知道你是否可以。
-
检查how-to-provide-a-reproducible-copy-of-the-dataframe-with-to-clipboard或添加
df.to_clipboard(sep=',', index=False)的输出 -
我认为您的数据有误。 id =
2的最后一行缺少列值。 -
不确定我是否理解正确,有一些行
sell_price是NaN。
标签: python-3.x pandas dataframe