【问题标题】:aggregating the table using pandas使用 pandas 聚合表
【发布时间】:2018-10-24 03:44:16
【问题描述】:

下面是输入。

            X   Y   Z
AP          1   1   1
Karnataka   0   1   0
Goa         1   1   0
Tamilnadu   0   1   0
AP          0   1   1
Goa         0   0   0
Tamilnadu   0   1   1
Goa         0   0   0
AP          1   0   0
Tamilnadu   0   1   0
Tamilnadu   1   1   0
Goa         0   1   1
Karnataka   0   0   0
Karnataka   0   1   0

要执行的计算:

  1. A 列中存在的状态数

  2. X 列中存在的 1 的数量除以 A 列中每个状态的计数

  3. 代码应该是动态的,因为列数和行数可能会有所不同。

预期输出:

                   Total      AP   Karnataka    Goa      Tamilnadu
Total Sample        14        3        3         4           4
X                 0.2857    0.6667  0.0000    0.2500      0.2500
Y                 0.7143    0.6667  0.6667    0.5000      1.0000
Z                 0.2857    0.6667  0.0000    0.2500      0.2500

【问题讨论】:

  • 你有什么尝试吗?

标签: python pandas


【解决方案1】:

我确信有更好的方法,但以下方法可行。

假设 my_df 有输入数据;

result=my_df.groupby('A').mean().transpose()
result1=my_df.groupby('A').sum().transpose()
result1=result1.append(my_df['A'].value_counts())
result1=result1.rename({'A':'Total Sample'})
result1['Total']=result1.apply('sum',axis=1)
finalRow=result1.iloc[len(result1)-1]
for i in range(len(result1)-1):
    result1.iloc[i]=result1.iloc[i]/finalRow
result['Total']=result1['Total']
result=result.append(result1.loc['Total Sample'])

完成!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2021-12-05
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2019-02-10
    • 2020-11-05
    相关资源
    最近更新 更多