英文:
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({'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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论