gpt4 book ai didi

python - 如何在数据帧之间随机分配值

转载 作者:太空狗 更新时间:2023-10-30 00:38:18 26 4
gpt4 key购买 nike

我正在尝试将一个数据框中的一列的值随机分配给 12 个不同类别(按年龄范围和性别)中的另一个数据框。例如我有两个数据框;让我们调用一个 d1 和另一个 d2

  d1:
index agerange gender income
0 2 1 56700
1 2 0 25600
2 4 0 3000
3 4 0 106000
4 3 0 200
5 3 0 43000
6 4 0 10000000

d2:
index agerange gender
0 3 0
1 2 0
2 4 0
3 4 0

我想按年龄范围和性别对两个数据框进行分组,即 0-1,2,3,4,5,6 & 1-1,2,3,4,5,6 然后随机选择 d1 中的收入之一并将其分配给 d2。

即:

d1:
index agerange gender income
0 2 1 56700
1 2 0 25600
2 4 0 3000
3 4 0 106000
4 3 0 200
5 3 0 43000
6 4 0 10000000

d2:
index agerange gender income
0 3 0 200
1 2 0 25600
2 4 0 10000000
3 4 0 3000

最佳答案

选项 1
使用 np.random.choicepd.DataFrame.query
的方法我做了一个隐含的假设,即我们为每一行替换随机抽取的值。

def take_one(x):
q = 'agerange == {agerange} and gender == {gender}'.format(**x)
return np.random.choice(d1.query(q).income)

d2.assign(income=d2.apply(take_one, 1))

agerange gender income
index
0 3 0 200
1 2 0 25600
2 4 0 106000
3 4 0 106000

选项 2
尝试提高每组调用一次 np.random.choice 的效率。

g = d1.groupby(['agerange', 'gender']).income.apply(list)
f = lambda x: pd.Series(np.random.choice(g.get(x.name, [0] * len(x)), len(x)), x.index)
d2.groupby(['agerange', 'gender'], group_keys=False).apply(f)

agerange gender income
index
0 3 0 200
1 2 0 25600
2 4 0 10000000
3 4 0 106000

调试和设置

import pandas as pd
import numpy as np

d1 = pd.DataFrame({
'agerange': [2, 2, 4, 4, 3, 3, 4],
'gender': [1, 0, 0, 0, 0, 0, 0],
'income': [56700, 25600, 3000, 106000, 200, 43000, 10000000]
}, pd.Index([0, 1, 2, 3, 4, 5, 6], name='index')
)

d2 = pd.DataFrame(
{'agerange': [3, 2, 4, 4], 'gender': [0, 0, 0, 0]},
pd.Index([0, 1, 2, 3], name='index')
)

g = d1.groupby(['agerange', 'gender']).income.apply(list)
f = lambda x: pd.Series(np.random.choice(g.loc[x.name], len(x)), x.index)
d2.assign(income=d2.groupby(['agerange', 'gender'], group_keys=False).apply(f))

       agerange  gender  income
index
0 3 0 200
1 2 0 25600
2 4 0 106000
3 4 0 3000

关于python - 如何在数据帧之间随机分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45421086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com