Skip to content

ENH: Construct pandas dataframe from function #33894

@giuliobeseghi

Description

@giuliobeseghi

It would be great if we could construct a pd.DataFrame from a function.

Describe the solution you'd like

import pandas as pd
import numpy as np

def my_random():
    return np.random.rand() + 1

df = pd.DataFrame(my_random, index=range(10), columns=range(15))

The output would be equivalent to

col_len = 10
index_len = 15
data = np.array([[my_random() for i in range(col_len)] for j in range(index_len)])
df = pd.DataFrame(data, index=range(index_len), columns=range(columns_len))

Alternatively, we could do the same with something like

df = pd.DataFrame.from_function(my_random, *args, **kwargs)

args and kwargs are passed to the df constructor.

EDIT

I just realized I can easily obtain what I want with

df = pd.DataFrame(index=range(10), columns=range(15)).applymap(
    lambda x: my_random()
)

It's quite compact and easy to read. It's slowish but I don't expect it to be used in high performance tasks.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions