【问题标题】:Running loop for frequency calculation in PythonPython中频率计算的运行循环
【发布时间】:2021-11-25 08:34:06
【问题描述】:

我有表格中显示的数据。我想使用 Python。对于 2016 年和 2017 年存在的所有果实,我想要这些果实在 2015 年的国家频率。

Country Fruit Year
Germany Apple 2015
France Apple 2015
France Apple 2015
Spain Apple 2015
Germany Banana 2015
France Banana 2015
France Apple 2016
Spain Apple 2016
Germany Banana 2016
France Banana 2016
France Banana 2017
France Grapes 2017

我想要的决赛桌如下所示:

Fruit Germany France Spain
Apple 1 2 1
Banana 1 1 0
Grapes 0 0 0

【问题讨论】:

  • Python 代码在哪里?你有解决这个问题的初步尝试吗?如果是这样,请将其包含在问题中。否则,StackOverflow 不是一个解决用户未进行初始尝试或在其代码中遇到困难的问题的网站。
  • 很抱歉我不知道。从下次开始会记住的。谢谢。
  • 别担心,一切都在tourhelp center,尤其是How do I ask and answer homework questions?

标签: python pandas loops dummy-variable


【解决方案1】:

按年份过滤,然后使用pivot_table 进行旋转:

(df[df.Year == 2015]
  .pivot_table('Year', 'Fruit', 'Country', aggfunc='count')
  .reindex(
    index=df.Fruit.unique(), 
    columns=df.Country.unique()
  ).fillna(0)
  .reset_index())

Country   Fruit  Germany  France  Spain
0         Apple      1.0     2.0    1.0
1        Banana      1.0     1.0    0.0
2        Grapes      0.0     0.0    0.0

另一种选择是使用crosstab,然后从结果中选择2015:

(pd.crosstab(df.Fruit, [df.Country, df.Year])
   .loc[:, pd.IndexSlice[:, 2015]]
   .droplevel(1, 1)
   .reset_index())

Country   Fruit  France  Germany  Spain
0         Apple       2        1      1
1        Banana       1        1      0
2        Grapes       0        0      0

【讨论】:

    【解决方案2】:

    试试:

    df_2015 = df[df['Year'] == 2015]
    pd.crosstab(df_2015['Fruit'], df_2015['Country']).reindex(df['Fruit'].unique(), fill_value=0)
    

    输出:

    Country  France  Germany  Spain
    Fruit                          
    Apple         2        1      1
    Banana        1        1      0
    Grapes        0        0      0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2011-06-27
      • 1970-01-01
      • 2015-01-07
      • 2021-04-05
      • 2011-03-24
      相关资源
      最近更新 更多