<p>你只需要几次换班就可以很好地做到这一点!您还可以使用此方法正确地获取索引,并将它们精确地添加到所需的位置。你知道吗</p>
<p>添加<code>Event</code>后,执行<code>DataFrame</code>:</p>
<pre><code>import pandas as pd
# Modify the index so we can later append to the correct rows
df.index= df.index*2
# Determine when switches occur
mask = (df.Driver != df.Driver.shift(1)) & (df.Car_ID == df.Car_ID.shift(1))
sw_from = df[mask.shift(-1).fillna(False)].copy()
sw_to = df[mask].copy()
# Make the switching rows have the correct information
sw_to['Event'] = sw_from.Driver.values + ' to ' + sw_to.Driver.values
sw_to['Driver'] = ''
# Modify the switching indices so they get added to the proper position
sw_to.index = sw_to.index+1
# Add them to df
df = df.append(sw_to).sort_index().reset_index(drop=True)
</code></pre>
<hr/>
<p>输出:</p>
<pre><code> Car_ID Date Driver Event
0 B332 2018-03-12 Alex Rent_Car_B
1 B332 2018-03-14 Alex Rent_Car_B
2 B332 2018-03-15 Mick Rent_Car_B
3 B332 2018-03-15 Alex to Mick
4 C315 2018-03-17 Sara Rent_Car_C
5 C315 2018-03-13 Sara Rent_Car_C
6 C315 2018-03-15 Jean Rent_Car_C
7 C315 2018-03-15 Sara to Jean
8 C315 2018-03-18 Sara Rent_Car_C
9 C315 2018-03-18 Jean to Sara
10 C315 2018-03-21 Sara Rent_Car_C
11 F310 2018-03-10 Franck Rent_Car_F
12 F310 2018-03-13 Michel Rent_Car_F
13 F310 2018-03-13 Franck to Michel
</code></pre>