我有一个包含汽车类型的列表,
a = ['Car_1','Car_1','Car_1','Car_2','Car_3','Car_3']
我应该能够从上面的列表中创建 2 个列表的输出,
result_count = [1,0,0,1,1,0] #Whenever new car type is present in list, make it 1
result_count = [1,2,3,1,1,2] #Count each car type
如何在不使用 for 循环的情况下轻松实现这一目标?谢谢。
最佳答案
IIUC,使用 pandas 数据框
对于#1,我们可以使用.drop_duplicates
对于#2,我们可以使用groupby
和cumcount
df = pd.DataFrame({'cars' : a})
one = (~df['cars'].duplicated()).astype(int).tolist() # Thanks to Erfan
two = (df.groupby('cars').cumcount() + 1).tolist()
print(one)
[1 0 0 1 1 0]
print(two)
[1, 2, 3, 1, 1, 2]
关于pandas - 如何计算列表数据的计数和首次出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60933762/