为了账号安全,请及时绑定邮箱和手机立即绑定

Python Dataframe 中的多个随机行

Python Dataframe 中的多个随机行

蝴蝶不菲 2023-04-11 15:26:38
我正在尝试制作一个自定义的随机数据模板,我可以在其中获得包含随机数据的一定数量的行(在本例中假设为 100 行),因为我经常需要此类数据进行测试。下面的代码给了我这个输出:   ID    Name  Age  City  Telephone    Birthday    1  Harold   60  4000   21327950  2020-07-29但我需要能够指定某处需要的行数,最好是在值随机化之前,因为我不想复制第 1 行 100 次然后对所有行进行迭代。我希望这在我当前使用的编码结构中是可能的,因为我希望模型尽可能灵活,以便在需要时可以顺利添加更多列。提前致谢!import pandas as pdimport datetimeimport numpy as npimport names# List of Columnsdata = {    'ID': 1,    'Name': names.get_first_name(names.get_full_name),    'Age': np.random.randint(18, 65),    'City': np.random.randint(2, 8)*1000,    'Telephone': np.random.randint(11111111, 99999999),    'Birthday': [datetime.date.today()],}# Create DataFramedf = pd.DataFrame(data)# Print the output.print(df)
查看完整描述

1 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

您可以使用列表理解。


import pandas as pd

import datetime

import numpy as np


# List of Columns

n = 100


data = {

    'ID': [i+1 for i in range(n)],

    'Age': [np.random.randint(18, 65) for i in range(n)],

    'City': [np.random.randint(2, 8)*1000 for i in range(n)],

    'Telephone': [np.random.randint(11111111, 99999999) for i in range(n)]

}


# Create DataFrame

df = pd.DataFrame(data)


# Print the output.

print(df)


>>>


     ID  Age  City  Telephone

0     1   43  6000   25571478

1     2   60  5000   89030075

2     3   33  7000   41082092

3     4   21  7000   95900727

4     5   64  3000   51121306

..  ...  ...   ...        ...

95   96   51  6000   21656354

96   97   46  3000   91976030

97   98   60  3000   58243519

98   99   41  3000   80755166

99  100   57  4000   96513484


[100 rows x 4 columns]


查看完整回答
反对 回复 2023-04-11
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信