Python global dataframe

In Python, a global DataFrame refers to a DataFrame object that is accessible and modifiable from anywhere within the code. This means that the DataFrame is not limited to a specific function or scope and can be used and manipulated throughout the program.

Here is an example of using a global DataFrame in Python:

import pandas as pd

# Create a global DataFrame
global_df = pd.DataFrame({'Name': ['John', 'Jane', 'Mike'],
                          'Age': [25, 30, 35],
                          'City': ['New York', 'London', 'Paris']})

In the above example, the global_df DataFrame is created outside of any function, making it accessible globally. It consists of columns for Name, Age, and City with corresponding data.

Since the global_df is not limited to any specific scope, it can be accessed and modified from any part of the program. For example, you can perform operations such as filtering, sorting, or appending data to the global DataFrame.

# Accessing and modifying the global DataFrame
print(global_df)
# Output:
#    Name  Age       City
# 0  John   25   New York
# 1  Jane   30     London
# 2  Mike   35      Paris

# Adding a new row to the global DataFrame
global_df = global_df.append({'Name': 'Kate', 'Age': 28, 'City': 'Berlin'}, ignore_index=True)

# Filtering the global DataFrame
filtered_df = global_df[global_df['Age'] > 25]

# Sorting the global DataFrame by Age
sorted_df = global_df.sort_values(by='Age')

print(filtered_df)
# Output:
#    Name  Age     City
# 1  Jane   30   London
# 2  Mike   35    Paris
# 3  Kate   28   Berlin

print(sorted_df)
# Output:
#    Name  Age       City
# 0  John   25   New York
# 3  Kate   28     Berlin
# 1  Jane   30     London
# 2  Mike   35      Paris

It’s important to note that while using global variables can provide convenience in terms of accessibility, it also introduces potential risks related to unintentional modifications or conflicts. It’s advisable to use global DataFrames carefully and consider alternative approaches when necessary.

Leave a comment