熊猫仍然是新手,但渴望学习。我有大约8000块农田的作物序列,描述了每年有哪些作物。我也有一个主要的作物名单,每一个可能的作物观察所有年份的数据。
对于每个“CropSeqYR”,我想得到独特作物的频率,然后确定与一个独特的作物类型相关的总面积(‘英亩’之和)。
作物序列数据的一个虚拟示例:
FieldID Acres CropSeq04 CropSeq05 CropSeq06
1 20 Barley Alfalfa Rye
2 30 Barley Rye Rye
3 45 Lettuce Alfalfa Beets
4 10 Hay Alfalfa Rye
5 15 Alfalfa Beets Beets
我所设想的产出将是:
Crops04 Freq04 Acre04 Crops05 Freq05 Acre05 Crops06 Freq06 Acre06
Alfalfa 1 15 Alfalfa 3 75 Beets 2 60
Barley 2 50 Beets 1 15 Rye 3 60
Hay 1 10 Rye 1 30
Lettuce 1 45
对于每种作物类型的英亩数和总和,我希望将这些值添加到我的“主”序列列表中,以确保行值匹配。NA值或空白是预期的,因为每年并不总是包含每种可能的作物类型。主序列列表的一个示例:
MasterCropList | Crops04 Freq04 Acre04 | Crops05 Freq05 Acre05 | Crops06 Freq06 Acre06
Alfalfa | Alfalfa 1 15 | Alfalfa 3 75 |
Barley | Barley 2 50 | |
Beets | | Beets 1 15 | Beets 2 60
Hay | Hay 1 10 | |
Rye | | Rye 1 30 | Rye 3 60
Lettuce | Lettuce 1 45 | |
我已经能够得到独特作物的频率,并分别对某一特定作物类型的英亩进行一年的汇总。然而,同时做这两件事使我无法逃脱。
总结和排序的英亩实例:
# Sums Acres per crop sequence
year04 = cropdf.groupby('Crop04', as_index=False)['Acres'].sum()
year04.sort_values(by=['Acres'], ascending=False)
我将继续探索如何将结果与基于共享值的主作物列表相结合。
发布于 2019-12-14 03:53:27
使用:
new_df= (
pd.concat([( group.add_suffix(i[-2:])
.rename(columns={'Crops':i})
.reset_index(drop=True) )
for i,group in ( df.melt(['FieldID','Acres'],
var_name='Seq',
value_name='Crops')
.groupby(['Seq','Crops'])
.Acres
.agg(Freq='size',Acre='sum')
.unstack('Seq')
.reindex(index=df_master['MasterCropList'])
.stack(dropna=False)
.swaplevel()
.sort_index()
.rename_axis(index=['Seq','Crops'])
.reset_index('Crops')
.assign(Crops=lambda x: x.Crops.where(x.Freq.notnull()))
.groupby(level=0) )],axis=1,sort=True)
)
df_master=( pd.concat([df_master.sort_values('MasterCropList')
.reset_index(drop=True),new_df],axis=1)
.fillna('') )
print(df_master)
输出
MasterCropList Crops04 Freq04 Acre04 Crops05 Freq05 Acre05 Crops06 Freq06 \
0 Alfalfa Alfalfa 1 15 Alfalfa 3 75
1 Barley Barley 2 50
2 Beets Beets 1 15 Beets 2
3 Hay Hay 1 10
4 Lettuce Lettuce 1 45
5 Rye Rye 1 30 Rye 3
Acre06
0
1
2 60
3
4
5 60
初始df_master
print(df_master)
MasterCropList
0 Alfalfa
1 Barley
2 Beets
3 Hay
4 Rye
5 Lettuce
如果所有的reindex
值都位于df1
的至少一列中,则不必使用
rename_axis
是not.
.add_suffix(i[-n:]
.https://stackoverflow.com/questions/59331528
复制相似问题