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 我要结婚祝福语简短
18 婚前女儿生日祝福语简短