在Python数据框的两列中随机选择两行

时间:2018-11-02 19:13:42

标签: python python-3.x pandas

原始数据框:

fruit   Drink     week
banana  milk      Mon
apple   coke      Tue
pear    tea       Wed

第二步使用以下代码:df['COMBINE'] = df['fruit']+ '+' +df['Drink']

fruit   Drink   COMBINE       week
banana  milk    banana+milk    Mon
apple   coke    apple+coke     Tue
pear    tea     pear+tea       Wed

第三步:

让它在COMBINE列中随机选择1行,在Week列中随机选择1行,然后将它们组合为字符串。

预期结果:

banana+milk Wed

我想知道如何将所有代码放在一起吗?

2 个答案:

答案 0 :(得分:4)

numpy.random.choice

df.apply(np.random.choice)

Food    milk
week     Tue
dtype: object

答案 1 :(得分:2)

以@piRSquared的answer为基础,并在修改后的问题中说明您的新要求:

import pandas as pd
import numpy as np

df = pd.DataFrame({'fruit': ['banana','apple','pear'], 'Drink': ['milk','coke','tea'], 'week': ['Mon','Tue','Wed']})

df['COMBINE'] = df['fruit'] + '+' + df['Drink']

' '.join(df[['COMBINE','week']].apply(np.random.choice).values)

收益:

apple+coke Mon