Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 一个字符串的平均值_Pandas_Pandas Groupby - Fatal编程技术网

Pandas 一个字符串的平均值

Pandas 一个字符串的平均值,pandas,pandas-groupby,Pandas,Pandas Groupby,我有一个示例DF: df = pd.DataFrame(np.random.randint(1,10,size=(6,3)),columns = list("ABC")) df["A"] = ["1111","2222","1111","1111","2222","1111"] df["B"] = ["20010101","20010101","20010101","20010101","20010201","20010201"] df 作品: 我试图找到B列的平均值,A列的grouby: 例

我有一个示例DF:

df = pd.DataFrame(np.random.randint(1,10,size=(6,3)),columns = list("ABC"))
df["A"] = ["1111","2222","1111","1111","2222","1111"]
df["B"] = ["20010101","20010101","20010101","20010101","20010201","20010201"]
df
作品:

我试图找到B列的平均值,A列的grouby:

例如:

考虑A列中的值“1111”:总交易:4,唯一交易:2(2001010120010201)。所以平均值是4/2=2

片段:

df.groupby("A",as_index=False).agg({"B":'mean'})
错误:

DataError: No numeric types to aggregate

找到这个的任何方法都意味着直接而不是进行分组和迭代

我不认为你想要的是“中庸”。试试这个:

df.groupby('A')['B'].apply(lambda x: x.count() / x.nunique())

A
1111    2.0
2222    1.0
Name: B, dtype: float64
或者,如果您不想使用apply,那么

grp = df.groupby('A')['B']
grp.count() / grp.nunique()

A
1111    2.0
2222    1.0
Name: B, dtype: float64
这是上面的一个单行程序,这个程序使用了
agg
和许多减速机:

df.groupby('A')['B'].agg(['count','nunique']).eval('count / nunique')

A
1111    2.0
2222    1.0
dtype: float64
df.groupby('A')['B'].agg(['count','nunique']).eval('count / nunique')

A
1111    2.0
2222    1.0
dtype: float64