1
def mean_type (df):
要求返回的数据是 'df' 每一列的平均值,和每一个唯一值
例子:
数据框
type a b c
index
0 x 1 0 1
1 x 0 0 1
2 y 1 0 1
输出
a b c
type
x 0.5 0.0 1.0
y 1.0 0.0 1.0
2
def last_type(df):
返回一个数据框,其中有'df'的最后一行和每一“type”里的唯一值
例子
数据框
type a b c
index
0 x 1 0 1
1 x 0 0 1
2 y 1 0 1
输出
a b c type
type
x 0 0 1 x
y 1 0 1 y
3
def last_type_org(df):
返回一个数据框,其中有'df'的最后一行和每一"type"里的唯一值,以及一个列名称为“org”该列的值是该行原始数据框的索引值
例子
数据框
type a b c
idx
0 x 1 0 1
1 x 0 0 1
2 y 1 0 1
输出
type a b c cor
type
x x 0 0 1 1
y y 1 0 1 2
import pandas
def mean_type(df):
return df.groupby('type').agg({'a': 'mean', 'b': 'mean', 'c': 'mean'})
def last_type(df):
last = df.groupby('type').last()
last['type'] = last.index
return last
def last_type_org(df):
df['cor'] = df.index
last = df.groupby('type').last()
last.insert(loc=0, column='type', value=last.index)
return last
if __name__ == '__main__':
df = pandas.DataFrame({'type': ['x', 'x', 'y'], 'a': [1, 0, 1], 'b': [0, 0, 0], 'c': [1, 1, 1]})
print(mean_type(df))
print("\r\n")
print(last_type(df))
print("\r\n")
print(last_type_org(df))