Reputation: 2607
I am trying to use a pandas dataframe global variable. However, the dataframe is empty when I try to reassign or append it to the global variable. Any help appreciated.
import pandas as pd
df = pd.DataFrame()
def my_func():
global df
d = pd.DataFrame()
for i in range(10):
dct = {
"col1": i,
"col2": 'value {}'.format(i)
}
d.append(dct, ignore_index=True)
# df.append(dct, ignore_index=True) # Does not seem to append anything to the global variable
df = d # does not assign any values to the global variable
my_func()
df.head()
Upvotes: 1
Views: 709
Reputation: 29742
As opposed to list.append
, pandas.DataFrame.append
is not an in-place operation. Slightly changing your code works as expected:
import pandas as pd
df = pd.DataFrame()
def my_func():
global df
d = pd.DataFrame()
for i in range(10):
dct = {
"col1": i,
"col2": 'value {}'.format(i)}
d = d.append(dct, ignore_index=True) # <<< Assignment needed
# df.append(dct, ignore_index=True) # Does not seem to append anything to the global variable
df = d # does not assign any values to the global variable
my_func()
df.head()
Output:
col1 col2
0 0.0 value 0
1 1.0 value 1
2 2.0 value 2
3 3.0 value 3
4 4.0 value 4
Upvotes: 2