我有一个大数据帧,看起来像这样:
+----------------------------------------------------------+
| Date Category Location ImpactRate |
+----------------------------------------------------------+
| 2018-04-22 Outage MT 0.05194 |
| 2018-04-22 Outage ND 0.02552 |
| 2018-04-22 Outage SD 0.09962 |
| 2018-04-24 Transport TX 0.03111 |
+----------------------------------------------------------+
我要做的是创建以下输出:
+-----------------------------------------------------------------------------------+
| Date Category ImpactRate Break Down |
+-----------------------------------------------------------------------------------+
| 2018-04-22 Outage 0.17708 MT (29.3%) SD (14.4%) ND (56.3%) |
| 2018-04-24 Transport 0.03111 TX (100.0%) |
+-----------------------------------------------------------------------------------+
第一次尝试-GroupBy
grouped_df = df.groupby('Date')['ImpactRate'].apply(list).apply(pd.Series).rename(columns=df['Location'])'
这将创建一个数据帧,其中包含每个位置都不存在的NAN,并创建需要格式化的其他列。你知道吗
第二次尝试-使用itertuples()循环:
r = []
for item in df.itertuples():
temp_x = df.loc[((df['Category'] == item[2]) & (df['Date'] == item[1]))
for i in range(temp_x.shape[0]):
r.append(temp_x['ImpactRate'].iloc[i])
这就产生了一个巨大的冲击率列表——这让我回到原点。你知道吗
我不知道如何解决这个问题。我猜我应该为每个迭代在一个列表中列出一个列表,但我一直在循环。我怎样才能以最具活力的方式实现这个输出呢?(请解释以便我能学习!)你知道吗
这是一种使用围绕
groupby.transform
的矢量化功能的方法。我将Breakdown
系列定义为元组列表,因为这是最灵活的格式。如果愿意,可以应用特定的字符串格式。你知道吗结果:
我觉得不太好。。但是哦,好吧。你知道吗
相关问题 更多 >
编程相关推荐