Python - 计算 Pandas DataFrame 中的第一个组值
要计算第一个组值,请使用该方法。首先,使用别名导入所需的库-groupby.first()
import pandas as pd;
创建一个包含3列的DataFrame-
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'BMW', 'Tesla', 'Lexus', 'Tesla'],"Place": ['Delhi','Bangalore','Pune','Punjab','Chandigarh','Mumbai'],"Units": [100, 150, 50, 80, 110, 90]
}
)现在,按列对DataFrame进行分组-
groupDF = dataFrame.groupby("Car")计算第一个组值并重置索引-
res = groupDF.first() res = res.reset_index()
示例
以下是完整的代码-
import pandas as pd;
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'BMW', 'Tesla', 'Lexus', 'Tesla'],"Place": ['Delhi','Bangalore','Pune','Punjab','Chandigarh','Mumbai'],"Units": [100, 150, 50, 80, 110, 90]
}
)
print("DataFrame ...\n",dataFrame)
#按列Car对DataFrame进行分组
groupDF = dataFrame.groupby("Car")
res = groupDF.first()
res = res.reset_index()
print("\nFirst of group values = \n",res)输出结果这将产生以下输出。显示第一次出现的重复值,即第一个组值-
DataFrame ...
Car Place Units
0 BMW Delhi 100
1 Lexus Bangalore 150
2 BMW Pune 50
3 Tesla Punjab 80
4 Lexus Chandigarh 110
5 Tesla Mumbai 90
First of group values =
Car Place Units
0 BMW Delhi 100
1 Lexus Bangalore 150
2 Tesla Punjab 80热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短