最近,我一直在使用Panda的DataFrames,并努力分析一些多维数据。
假设我有如下数据:
order | sample | feature1 | feature2
-------------------------------------
1234 | A | 0.20 | 0.45
1234 | B | 0.71 | 0.08
1234 | C | 0.21 | 0.02
1234 | D | 0.87 | 0.88
5678 | A | 0.76 | 0.42
5678 | B | 0.01 | 0.03
5678 | C | 0.29 | 0.91
5678 | D | 0.70 | 0.78
我想在输出中按顺序分组所有内容,并按示例汇总每个功能:
order | feature1 | feature2
| A | B | C | D | A | B | C | D
------------------------------------------------------------
1234 | 0.20 | 0.71 | 0.21 | 0.87 | 0.45 | 0.08 | 0.02 | 0.88
5678 | 0.76 | 0.01 | 0.29 | 0.70 | 0.42 | 0.03 | 0.91 | 0.78
这是我到目前为止的内容:
from pandas import *
df = DataFrame({"order": [1234, 1234, 1234, 1234, 5678, 5678, 5678, 5678], "sample": ["A", "B", "C", "D", "A", "B", "C", "D"], "feature1": [0.20, 0.71, 0.21, 0.87, 0.76, 0.01, 0.29, 0.70], "feature2": [0.45, 0.08, 0.02, 0.88, 0.42, 0.03, 0.91, 0.78]})
byorder = df.groupby("order")
# not sure how to go from 1 groupby object to a new dataframe having what i need
您是否对如何最终获得一个包含所需聚合数据的新DataFrame有任何想法?也许DataFrames不是执行这种操作的正确工具?
您可以使用 pivot
>>> df.pivot(index='order', columns='sample')
feature1 feature2
sample A B C D A B C D
order
1234 0.20 0.71 0.21 0.87 0.45 0.08 0.02 0.88
5678 0.76 0.01 0.29 0.70 0.42 0.03 0.91 0.78
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句