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,

  • What are `propname` and `propval`? – G. Anderson Apr 19 '22 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] – Akashdas221 Apr 19 '22 at 17:34
  • Updated my message with a detailed description of the reason. – inquirer May 01 '22 at 11:40

2 Answers2

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
inquirer
  • 4,286
  • 2
  • 9
  • 16
  • I need to define the DataFrame to use globally. propName and propValue are local variables used within a for-loop. Any tips? – Akashdas221 Apr 19 '22 at 18:20
  • Initialize with some specific values, and then replace them with the necessary ones. If you have a pre-known number of values for columns? – inquirer Apr 19 '22 at 18:35
  • Thanks, that works! Can you explain why your code works, but mine didn't? New to this and want to learn. – Akashdas221 Apr 19 '22 at 18:43
  • As far as I understand, an empty dataframe has no) [index](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.empty.html) – inquirer Apr 19 '22 at 19:09
  • 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. – Akashdas221 Apr 19 '22 at 20:46
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.