mauve
mauve

Reputation: 2763

DataFrame empty mysteriously - but why?

Is there something special about creating a DataFrame with strings that makes it not actually take the values? I'm at a loss as to how to even troubleshoot this.

df = pd.DataFrame()
df['Jan Total'] = '=SUM(B2:B32)'
df['Feb Total'] = '=SUM(C2:C32)'
... 
df['Yearly Total'] = '=SUM(B2:M32)'
df['Total in Gallons'] = '=SUM(B2:M32)/0.264172'

print(df)

Empty DataFrame
Columns: [Jan Total, Feb Total, Mar Total, April Total, May Total, June Total, July Total, Aug Total, Sep Total, Oct Total, Nov Total, Dec Total, Yearly Total, Total in Gallons]
Index: []

Upvotes: 0

Views: 55

Answers (1)

furas
furas

Reputation: 142631

Code

df['Jan Total'] = '=SUM(B2:B32)'

tries to replace values in all existing cells in column 'Jan Total' but you don't have rows so it can't replace them. It doesn't create new row.

You can assign value(s) using list

df['Jan Total'] = ['=SUM(B2:B32)']

df['Jan Total'] = ['=SUM(B2:B32)', 'value in second row']

You can also create DataFrame with row and then replace values

import pandas as pd

df = pd.DataFrame([[]])

df['Jan Total'] = '=SUM(B2:B32)'

df['Jan Total'] = '=SUM(B2:B32)'
df['Feb Total'] = '=SUM(C2:C32)'
... 
df['Yearly Total'] = '=SUM(B2:M32)'
df['Total in Gallons'] = '=SUM(B2:M32)/0.264172'

print(df)

Result:

      Jan Total     Feb Total  Yearly Total       Total in Gallons
0  =SUM(B2:B32)  =SUM(C2:C32)  =SUM(B2:M32)  =SUM(B2:M32)/0.264172

But if you have more rows - pd.DataFrame([[], []]) - then it will replace it in all rows

import pandas as pd

df = pd.DataFrame([[], []])

df['Jan Total'] = '=SUM(B2:B32)'

df['Jan Total'] = '=SUM(B2:B32)'
df['Feb Total'] = '=SUM(C2:C32)'
... 
df['Yearly Total'] = '=SUM(B2:M32)'
df['Total in Gallons'] = '=SUM(B2:M32)/0.264172'

print(df)

Result

      Jan Total     Feb Total  Yearly Total       Total in Gallons
0  =SUM(B2:B32)  =SUM(C2:C32)  =SUM(B2:M32)  =SUM(B2:M32)/0.264172
1  =SUM(B2:B32)  =SUM(C2:C32)  =SUM(B2:M32)  =SUM(B2:M32)/0.264172

Upvotes: 3

Related Questions