我有一个pandas数据框,看起来像这样:
df = pd.DataFrame({'Name' : ['Kate', 'John', 'Peter','Kate', 'John', 'Peter'],'Distance' : [23,16,32,15,31,26], 'Time' : [3,5,2,7,9,4]})
df
Distance Name Time
0 23 Kate 3
1 16 John 5
2 32 Peter 2
3 15 Kate 7
4 31 John 9
5 26 Peter 2
我想添加一个列,告诉我,对于每个名字,时间的顺序是什么。在
我想要这样的东西:
^{pr2}$我可以使用for循环:
df2 = df[df['Name'] == 'aaa'].reset_index().reset_index() # I did this just to create an empty data frame with the columns I want
for name, row in df.groupby('Name').count().iterrows():
table = df[df['Name'] == name].sort_values('Time').reset_index().reset_index()
to_concat = [df2,table]
df2 = pd.concat(to_concat)
df2.drop('index', axis = 1, inplace = True)
df2.columns = ['Order', 'Distance', 'Name', 'Time']
df2
这是可行的,问题是(除了非常不协调外),对于大型表(我的实际表大约有5万行),运行大约需要半小时。在
有人能帮我用一种更简单、运行速度更快的方式写这篇文章吗? 很抱歉,如果这个问题在某个地方得到了回答,但我真的不知道如何去寻找它。在
最好的
PS我不确定这是最优雅的方式来做这个。。。在
将^{} 与^{} 一起使用:
如果需要第一列,请使用^{} :
^{pr2}$相关问题 更多 >
编程相关推荐