求连胜的问题,前边有人求助,找不到那个帖子了
本帖最后由 rsj0315 于 2021-5-27 21:02 编辑求各个id的连胜场次最大值
一列是用户id 一列是战斗情况 战斗情况为胜 负,平,局;
胜就是1 ,用python看每个用户的最大连胜数
方法一
import pandas as pd
def List_deal(list_waitdeal):
max_time = 0# 已知最大连续出现次数初始为0
cur_time = 1# 记录当前元素是第几次连续出现
pre_element = None# 记录上一个元素是什么
for i in list_waitdeal:
if i == pre_element:# 如果当前元素和上一个元素相同,连续出现次数+1,并更新最大值
cur_time += 1
max_time = max((cur_time, max_time))
else:# 不同则刷新计数器
pre_element = i
cur_time = 1
return max_time
if __name__ == '__main__':
import time
start = time.time()
df=pd.read_excel(r'连胜情况.xlsx')
ID_list=list(set(df['ID']))
Result = {}
for i in range(len(ID_list)):
df_pre=df==ID_list]
# print(list(df_pre['胜负']))
Max_time=List_deal(list(df_pre['胜负']))
Result]=Max_time
Result_df = pd.DataFrame.from_dict(Result,orient='index',columns=['连胜最多场次'])
Result_df.to_excel(r'final_deal.xlsx')
end = time.time()
print(end - start)
方法二
import pandas as pd
def List_deal(list_waitdeal):
max_time = 0# 已知最大连续出现次数初始为0
cur_time = 1# 记录当前元素是第几次连续出现
pre_element = None# 记录上一个元素是什么
for i in list_waitdeal:
if i == pre_element:# 如果当前元素和上一个元素相同,连续出现次数+1,并更新最大值
cur_time += 1
max_time = max((cur_time, max_time))
else:# 不同则刷新计数器
pre_element = i
cur_time = 1
return max_time
if __name__ == '__main__':
import time
start = time.time()
df=pd.read_excel(r'连胜情况.xlsx')
ds1=df.groupby('ID')
df2 = dict(list(ds1))#这部操作,有点不太懂
print(df2)
Result={}
for i in df2.keys():
df_pre2 = pd.DataFrame(df2, index=None)
Max_time=List_deal(list(df_pre2['胜负']))
Result=Max_time
Result_df = pd.DataFrame.from_dict(Result,orient='index',columns=['连胜最多场次'])
Result_df.to_excel(r'final_deal.xlsx')
end = time.time()
print(end - start)
方法二的查询各id数据方法,挺好的,效率高一些 又有好朋友提供一个好的办法
import pandas as pd
df = pd.DataFrame({'胜': })
print(df)
df['连胜'] = 0
df.loc = df.loc
for i in df.index:
if i == 0:
continue
if df.loc == 1:
df.loc = 1 + df.loc
else:
df.loc = 0
print(df)
print('最大连胜', df['连胜'].max())
页:
[1]