4

I have information on total number of rows and number of columns for a new pandas dataframe

import pandas as pd
nRow = 10
nCol = 4

Based on this information I want to create a new dataframe where each element will be filled by 1

Is there any direct method available with pandas to achieve this?

1
  • Beside the point, but this smells like an XY problem. What's the end goal? E.g. if your data isn't labeled and is all the same dtype, a NumPy array might be more appropriate, like in Paul's answer without the dataframe wrapping it. Commented Oct 22 at 1:56

3 Answers 3

7

Another possible solution, which uses np.ones to create an array of ones with which to create the wanted dataframe:

pd.DataFrame(np.ones((nRow,nCol)))
Sign up to request clarification or add additional context in comments.

Comments

5

There is no such method in pandas, but you could create the DataFrame in one line like this

df = pd.DataFrame(1, index=range(nRow), columns=range(nCol))

Comments

2

I can't think of a direct method in pandas.

You can do something like this.

import numpy as np

# Generate custom but automatic column names
cols = [f"Col{i+1}" for i in range(nCol)]

# Create the DataFrame
df = pd.DataFrame(np.nan, index=range(nRow), columns=cols)

1 Comment

This is not full of ones

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.