'how to group uneven data frame by condition
I am wondering is there a thing with a unique or other function/method for pandas to slice a table where I have a pattern:
1.0, 2.0, 2.1,
1.0, 2.2, 2.0,
1.0, 2.3, 1.9,
1.5, 2.1, 2.0
1.5, 1.8, 1.9,
...
uneven table with 1st column as an indicator of where to group/slice lines.
Loop/ group it for array/list/whatever that contains values of 1.0, 1.5 grouped together I was trying to get
array1 as:
1.0, 2.0, 2.1
1.0, 2.2, 2.0
1.0, 2.3, 1.9
array_2
1.5, 2.1, 2.0
1.5, 1.8, 1.9
I tried first_col = df.iloc[:, 0].tolist()
but it is not what I would need.
Solution 1:[1]
If need loop by groups by first column use:
for i, g in df.groupby(df.columns[0]):
print (g.mean().to_numpy())
If need list of DataFrames:
L = [g for i, g in df.groupby(df.columns[0])]
If need dictionary of DataFrames:
d = dict(tuple(df.groupby(df.columns[0])))
EDIT:
Simpliest is new column:
df['avg'] = df.mean(axis=1)
For arrays per groups:
for i, g in df.groupby(df.columns[0]):
print (g.mean().to_numpy())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
