从对象列(在我看来,该列的每个单元格就像一个有两个数字的矩阵)我想计算每个单元格的平均值:
> appid new_owners
> 10 [10000000, 20000000]
> 20 [5000000, 10000000]
> 30 [5000000, 10000000]
> 40 [5000000, 10000000]
> 50 [5000000, 10000000]
现在我想要的是这样的:
> appid new_owners
> 10 15000000
> 20 7500000
> 30 7500000
> 40 7500000
> 50 7500000
我会按照以下方式做
import pandas as pd
import statistics
df = pd.DataFrame({"appid":[10,20,30,40,50],"new_owners":[[10000000, 20000000], [5000000, 10000000], [5000000, 10000000], [5000000, 10000000], [5000000, 10000000]]})
df["new_owners"] = df["new_owners"].apply(statistics.mean)
print(df)
输出
appid new_owners
0 10 15000000
1 20 7500000
2 30 7500000
3 40 7500000
4 50 7500000
pandas.Series.apply
和 statistics.mean
函数(statistics
是 python
标准库的一部分)
我将扩展 Daweo 的 answer 来处理每个单元格包含 strings 列表(而不是浮点数或整数)的情况:
import pandas as pd
import statistics
mapping_dict = {'A':['1','2','3'], 'B':['3','4','5']}
df = pd.DataFrame(list(mapping_dict.items()),columns=['Key','Value'])
print(df["Value"])
df["Value"] = df["Value"].apply(lambda s: list(map(float, s)))
df["Value"] = df["Value"].apply(statistics.mean)
print(df["Value"])
输出:
0 [1, 2, 3]
1 [3, 4, 5]
Name: Value, dtype: object
0 2.0
1 4.0
Name: Value, dtype: float64