有没有更好的方法来创建一个类,该类生成人口的随机性别,并根据n分配给社区?

2024-09-28 01:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

Python类,该类生成人口的随机性别(M/F),并基于n将其分配给社区

  1. 人口数量=30

  2. 示例人口计数为30(成人、老年人、儿童)

  3. 年龄分布成人50%,儿童30%,年龄20%

  4. 社区数据

       Community_num    Community_name  Community_polygon   Community_population
       301              new york        Mutipolgon([])      10
       303              JFK             Mutipolgon([])      10
       304              River side      Mutipolgon([])      10
    

预料之外

 Community_num  Community_name  Community_polygon   Community_population Gender Age  Age_Group 

  301               new york        Mutipolgon([])      10                F      27 Adult
  301               new york        Mutipolgon([])      10                M      27 Adult
  301               new york        Mutipolgon([])      10                M      10 Kids
  301               new york        Mutipolgon([])      10                M      50 Old

代码尝试

def GeneratePeople(time, n):
   
    people = [None] * n
   
    for i in range(0,n):
       
        people[i] = Person(Gender.Male, 30, time)
       
       
    return people

我有基本的,但我需要帮助

年龄

kids - below 15
adult - above 15 to 45
old  - 45 above

Tags: namecommunitynewgenderpeople社区num儿童
1条回答
网友
1楼 · 发布于 2024-09-28 01:24:19

有一种方法可以做到这一点:

df["dummy"] = df.Community_population.map(lambda x: list(range(x)))
df = df.explode("dummy")
df["Gender"] = np.random.choice(["M", "F"], len(df))

df["Age_Group"] = np.random.choice(["child", "adult", "old"], len(df), p=[.3, .5, .2])
df.loc[df.Age_Group == "old", "age"] = np.random.randint(50, 90, len(df[df.Age_Group == "old"] ))

df.loc[df.Age_Group == "child", "age"] = np.random.randint(0, 18, len(df[df.Age_Group == "child"] ))
df.loc[df.Age_Group == "adult", "age"] = np.random.randint(18, 50, len(df[df.Age_Group == "adult"] ))

结果:

enter image description here

相关问题 更多 >

    热门问题