使用循环从单个数据框中获取不同的数据框

huangapple go评论70阅读模式
英文:

Getting a different dataframe from single dataframe using a loop

问题

我有一个数据框:

类型 子类型 数量
A AA 10
A AA 5
B AA 9
B BA 4
B BA 5
A BA 2
B CA 8
B CA 5
A CA 3

我希望根据子类型将数据框拆分。

输出的数据框应该是:

类型 子类型 数量
A AA 10
A AA 5
B AA 9
类型 子类型 数量
B BA 4
B BA 5
A BA 2
类型 子类型 数量
B CA 8
B CA 5
A CA 3
英文:

I have a dataframe:

Type Sub_Type Count
A AA 10
A AA 5
B AA 9
B BA 4
B BA 5
A BA 2
B CA 8
B CA 5
A CA 3

I want the dataframes to be split according to the Sub_type.

The output dataframes should be:

Type Sub_Type Count
A AA 10
A AA 5
B AA 9
Type Sub_Type Count
B BA 4
B BA 5
A BA 2
Type Sub_Type Count
B CA 8
B CA 5
A CA 3

答案1

得分: 1

import pandas as pd

df = pd.DataFrame({'Type': ["A", "A", "B", "B", "B", "A"],
                   'Sub_Type': ["AA", "AA", "BA", "BA", "AA", "BA"],
                   'Count': [3, 9, 3, 4, 3, 1]})

datdict = {}
i = 0
for frame, data in df.groupby(['Type', 'Sub_Type']):
    datdict[i] = data
    i += 1
Dataframe 0 for instance:
print(pd.DataFrame(datdict[0]))

  Type Sub_Type  Count
0    A       AA      3
1    A       AA      9
Datadict contains:
>>> datdict
{0:   Type Sub_Type  Count
0    A       AA      3
1    A       AA      9, 1:   Type Sub_Type  Count
5    A       BA      1, 2:   Type Sub_Type  Count
4    B       AA      3, 3:   Type Sub_Type  Count
2    B       BA      3
3    B       BA      4}

<details>
<summary>英文:</summary>

```python
import pandas as pd

df = pd.DataFrame({&#39;Type&#39;: [&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;A&quot;],
                    &#39;Sub_Type&#39;: [&quot;AA&quot;, &quot;AA&quot;, &quot;BA&quot;, &quot;BA&quot;, &quot;AA&quot;, &quot;BA&quot;],
                    &#39;Count&#39;: [3, 9, 3, 4, 3, 1],
                    })

datdict = {}
i = 0
for frame, data in df.groupby([&#39;Type&#39;, &#39;Sub_Type&#39;]):
    datdict[i] = data
    i+=1
Dataframe 0 for instance :
print(pd.DataFrame(datdict[0]))

  Type Sub_Type  Count
0    A       AA      3
1    A       AA      9
Datadict contains :
&gt;&gt;&gt; datdict
{0:   Type Sub_Type  Count
0    A       AA      3
1    A       AA      9, 1:   Type Sub_Type  Count
5    A       BA      1, 2:   Type Sub_Type  Count
4    B       AA      3, 3:   Type Sub_Type  Count
2    B       BA      3
3    B       BA      4}

huangapple
  • 本文由 发表于 2023年2月20日 00:55:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定