1

Essentially, I would like to add values to certain columns in an empty DataFrame with defined columns, but when I run the code, I get.

Empty DataFrame
Columns: [AP, AV]
Index: []

Code:

df = pd.DataFrame(columns=['AP', 'AV'])  
df['AP'] = propName 
df['AV'] = propVal

I think this could be a simple fix, but I've tried some different solutions to no avail. I've tried adding the values to an existing dataframe I have, and it works when I do that, but would like to have these values in a new, separate structure.

Thank you,

3
  • What are propname and propval? Commented Apr 19, 2022 at 17:34
  • @G.Anderson PropName and propVal are values pulled from a DataFrame I'm reading in from Excel called propData: propName = propData.iloc[1, 0] idx = propData.index[propData[0] == 'Total Unleveraged Present Value'].tolist()[0] propVal = propData.iloc[idx, 1] Commented Apr 19, 2022 at 17:34
  • Updated my message with a detailed description of the reason. Commented May 1, 2022 at 11:40

2 Answers 2

2

It's the lack of an index. If you create an empty dataframe with an index.

df = pd.DataFrame(index = [5])

Output

Empty DataFrame
Columns: []
Index: [5]

Then when you set the value, it will be set.

df[5] = 12345

Output

       5
5  12345

You can also create an empty dataframe. And when setting a column with a value, pass the value in the list. The index will be automatically set.

df = pd.DataFrame()
df['qwe'] = [777]

Output

   qwe
0  777
Sign up to request clarification or add additional context in comments.

5 Comments

I need to define the DataFrame to use globally. propName and propValue are local variables used within a for-loop. Any tips?
Initialize with some specific values, and then replace them with the necessary ones. If you have a pre-known number of values for columns?
Thanks, that works! Can you explain why your code works, but mine didn't? New to this and want to learn.
As far as I understand, an empty dataframe has no) index
Understood, but I thought me assigning a value would no longer make the dataframe empty? For example, I initialize another empty dataframe, and then populate that dataframe with data from yet another dataframe, and that works with no issues.
0

Assign propName and propValue to dictionary:

dict = {}
dict[propName] = propValue

Then, push to empty DataFrame, df:

df = pd.DataFrame()
df['AP'] = dict.keys()
df['AV'] = dict.values()

Probably not the most elegant solution, but works great for me.

Comments

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.