擅长:python、mysql、java
<p>您不需要groupby来创建uniqueID,您可以稍后对uniqueID进行groupby,以获得基于年龄和国籍的组。我使用了一个自定义函数来构建文本str。这是一种方法。你知道吗</p>
<pre><code>df1 = df.assign(uniqueID='ID_'+df.Nationality+df.age.astype(str))
def myText(x):
str = ' and '.join(x.Name)
str += ' have a combined age of {}.'.format(x.age.sum())
return str
df2 = df1.groupby(['uniqueID', 'Nationality','age']).apply(myText).reset_index().rename(columns={0:'Text'})
print(df2)
</code></pre>
<p>输出:</p>
<pre><code> uniqueID Nationality age Text
0 ID_UK28 UK 28 Peter and Wiley have a combined age of 56.
1 ID_US29 US 29 John and Aster have a combined age of 58.
</code></pre>