How To Dataframe.groupby Along Axis=1
Solution 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
01.012.021.5
Solution 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' forxin df1.columns}, axis=1).mean()
mean
01.012.021.5
Solution 3:
Given the original dataframe df
as follows -
AB C
011212232 -361
Please use command
df.groupby(by=lambda x : df[x].loc[0],axis=1).mean()
to get the desired output as -
1 2
0 1.0 2.0
1 2.0 3.0
2 1.5 1.0
Here, the function lambda x : df[x].loc[0]
is used to map columns A
and B
to 1
and column C
to 2
. This mapping is then used to decide the grouping.
You can also use any complex function defined outside the groupby
statement instead of the lambda
function.
Solution 4:
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
Post a Comment for "How To Dataframe.groupby Along Axis=1"