How to DataFrame.groupby along axis=1

好久不见. 提交于 2021-01-27 08:19:41

问题


I have:

df = pd.DataFrame({'A':[1, 2, -3],'B':[1,2,6]})
df
    A   B
0   1   1
1   2   2
2   -3  6

Q: How do I get:

    A
0   1
1   2
2   1.5

using groupby() and aggregate()?

Something like,

df.groupby([0,1], axis=1).aggregate('mean')

So basically groupby along axis=1 and use row indexes 0 and 1 for grouping. (without using Transpose)


回答1:


Are you looking for ?

df.mean(1)
Out[71]: 
0    1.0
1    2.0
2    1.5
dtype: float64

If you do want groupby

df.groupby(['key']*df.shape[1],axis=1).mean()
Out[72]: 
   key
0  1.0
1  2.0
2  1.5



回答2:


Grouping keys can come in 4 forms, I will only mention the first and third which are relevant to your question. The following is from "Data Analysis Using Pandas":

Each grouping key can take many forms, and the keys do not have to be all of the same type:

• A list or array of values that is the same length as the axis being grouped

•A dict or Series giving a correspondence between the values on the axis being grouped and the group names

So you can pass on an array the same length as your columns axis, the grouping axis, or a dict like the following:

df1.groupby({x:'mean' for x in df1.columns}, axis=1).mean()

    mean
0   1.0
1   2.0
2   1.5



回答3:


try this:

df["A"] = np.mean(dff.loc[:,["A","B"]],axis=1)
df.drop(columns=["B"],inplace=True)
      A
 0   1.0
 1   2.0
 2   1.5


来源:https://stackoverflow.com/questions/47963927/how-to-dataframe-groupby-along-axis-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!