Python Dataframe 中的多个随机行

我正在尝试制作一个自定义的随机数据模板,我可以在其中获得包含随机数据的一定数量的行(在本例中假设为 100 行),因为我经常需要此类数据进行测试。下面的代码给了我这个输出:


   ID    Name  Age  City  Telephone    Birthday

    1  Harold   60  4000   21327950  2020-07-29

但我需要能够指定某处需要的行数,最好是在值随机化之前,因为我不想复制第 1 行 100 次然后对所有行进行迭代。我希望这在我当前使用的编码结构中是可能的,因为我希望模型尽可能灵活,以便在需要时可以顺利添加更多列。提前致谢!


import pandas as pd

import datetime

import numpy as np

import names


# List of Columns

data = {

    '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 DataFrame

df = pd.DataFrame(data)


# Print the output.

print(df)


蝴蝶不菲
浏览 126回答 1
1回答

温温酱

您可以使用列表理解。import pandas as pdimport datetimeimport numpy as np# List of Columnsn = 100data = {    '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 DataFramedf = pd.DataFrame(data)# Print the output.print(df)>>>     ID  Age  City  Telephone0     1   43  6000   255714781     2   60  5000   890300752     3   33  7000   410820923     4   21  7000   959007274     5   64  3000   51121306..  ...  ...   ...        ...95   96   51  6000   2165635496   97   46  3000   9197603097   98   60  3000   5824351998   99   41  3000   8075516699  100   57  4000   96513484[100 rows x 4 columns]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python