擅长:python、mysql、java
<p>不确定这是否是您要寻找的,但它呈现的结果与您正在寻找的结果相同。请注意,我在同一列上使用多个聚合函数,因此使用ravel函数来展平数据帧列。在</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'ID':[1,1,1,1],
'Col1':['A','A','B','C'],
'Col2':[50,52,45,18]})
df = df.groupby(['ID','Col1']).agg({'Col2':['first','last']})
df.columns = ["_".join(x) for x in df.columns.ravel()]
df = df.reset_index()
df['Col2_last'] = np.where(df.Col2_first == df.Col2_last, float('nan'), df.Col2_last)
print(df)
</code></pre>