Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Wednesday, June 5, 2024

Exploring Python Data Structures: Lists, Tuples, Dictionaries, Sets, and DataFrames - Part 1 -

Introduction to Python Data Structures

Python, with its simplicity and versatility, offers a plethora of data structures to suit various programming needs. Understanding these data structures is fundamental for any Python programmer to efficiently manipulate, store, and retrieve data. In this series, we will delve into the most commonly used Python data structures: Lists, Tuples, Dictionaries, Sets, and DataFrames. Each part will explore one of these data structures, providing insights into their characteristics, use cases, and code examples.

Overview of Python Data Structures:

Before we delve into the specifics of each data structure, let's briefly overview them:

  1. Lists: Lists are ordered collections of items, allowing duplicates, and are mutable, meaning their elements can be changed after creation.
  2. Tuples: Tuples are similar to lists but are immutable, meaning their elements cannot be changed after creation.
  3. Dictionaries: Dictionaries are collections of key-value pairs, providing fast lookup based on keys.
  4. Sets: Sets are unordered collections of unique elements, useful for performing mathematical set operations like union, intersection, and difference.
  5. DataFrames: DataFrames are two-dimensional labeled data structures, commonly used for data manipulation and analysis, especially in data science tasks.


1. Understanding Lists:

Lists are perhaps the most versatile data structure in Python. They can contain any number of elements of different types and can be easily modified. Let's explore some examples to understand lists better.

Code Example: Lists


# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]

# Creating a list of strings
fruits = ['apple', 'banana', 'orange']

# Creating a list of mixed types
mixed = [1, 'apple', True, 3.14]

# Accessing elements of a list
print(numbers[0])  # Output: 1
print(fruits[1])   # Output: banana

# Modifying elements of a list
fruits[0] = 'pear'
print(fruits)      # Output: ['pear', 'banana', 'orange']

# Adding elements to a list
fruits.append('grape')
print(fruits)      # Output: ['pear', 'banana', 'orange', 'grape']

Conclusion

Lists are a fundamental data structure in Python, offering flexibility and ease of use. In the next part, we'll explore tuples, another essential data structure in Python.

2. Understanding Tuples:

Tuples are another important data structure in Python, similar to lists but with some key differences. Unlike lists, tuples are immutable, meaning once they are created, their elements cannot be changed. Let's explore some examples to understand tuples better.

Code Example: Tuples


# Creating a tuple of numbers
numbers = (1, 2, 3, 4, 5)

# Creating a tuple of strings
fruits = ('apple', 'banana', 'orange')

# Creating a tuple of mixed types
mixed = (1, 'apple', True, 3.14)

# Accessing elements of a tuple
print(numbers[0])  # Output: 1
print(fruits[1])   # Output: banana

Tuples are immutable, meaning once they are created, their elements cannot be changed. Attempting to modify a tuple or add elements to it will result in an error.

Conclusion

Tuples provide immutability and are useful for representing fixed collections of items. In the next part, we'll explore dictionaries, another essential data structure in Python.

3. Understanding Dictionaries:

Dictionaries are versatile data structures in Python that store key-value pairs. Unlike sequences such as lists and tuples, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be of any immutable type. Let's explore some examples to understand dictionaries better.

Code Example: Dictionaries


# Creating a dictionary of key-value pairs
student = {'name': 'Alice', 'age': 25, 'grade': 'A'}

# Accessing values using keys
print(student['name'])   # Output: Alice
print(student['age'])    # Output: 25

# Adding a new key-value pair
student['city'] = 'New York'
print(student)           # Output: {'name': 'Alice', 'age': 25, 'grade': 'A', 'city': 'New York'}

# Modifying a value
student['age'] = 26
print(student)           # Output: {'name': 'Alice', 'age': 26, 'grade': 'A', 'city': 'New York'}

# Deleting a key-value pair
del student['grade']
print(student)           # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}

Conclusion

Dictionaries are powerful data structures for organizing and retrieving data based on keys. They are widely used in various Python applications for tasks such as storing configuration settings, caching results, and representing structured data. In the next part, we'll explore sets, another important data structure in Python.

4. Understanding Sets:

Sets are unordered collections of unique elements in Python. They are useful for tasks that require membership testing or eliminating duplicate entries. Unlike lists and tuples, which are ordered collections, sets do not maintain the order of elements. Let's explore some examples to understand sets better.

Code Example: Sets


# Creating a set of unique numbers
numbers = {1, 2, 3, 4, 5}

# Creating a set from a list (eliminates duplicates)
numbers_list = [1, 2, 3, 3, 4, 5]
unique_numbers = set(numbers_list)
print(unique_numbers)   # Output: {1, 2, 3, 4, 5}

# Adding elements to a set
numbers.add(6)
print(numbers)          # Output: {1, 2, 3, 4, 5, 6}

# Removing elements from a set
numbers.remove(3)
print(numbers)          # Output: {1, 2, 4, 5, 6}

Conclusion

Sets are valuable data structures for tasks that require unique elements or membership testing. They offer efficient methods for set operations such as union, intersection, and difference. In the next part, we'll explore DataFrames, a powerful data structure provided by libraries like Pandas for data manipulation and analysis.

5. Understanding DataFrames:

DataFrames are two-dimensional labeled data structures provided by libraries like Pandas in Python. They are widely used for data manipulation and analysis tasks, especially in data science and machine learning applications. Let's explore some examples to understand DataFrames better.

Code Example: DataFrames


import pandas as pd

# Creating a DataFrame from a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
print(df)
# Output:
#      Name  Age         City
# 0   Alice   25     New York
# 1     Bob   30  Los Angeles
# 2 Charlie   35      Chicago

# Accessing columns of a DataFrame
print(df['Name'])   # Output: 0     Alice
                    #          1       Bob
                    #          2    Charlie
                    #          Name: Name, dtype: object

# Accessing rows of a DataFrame
print(df.iloc[0])   # Output: Name        Alice
                    #          Age            25
                    #          City    New York
                    #          Name: 0, dtype: object

Conclusion

DataFrames provide a powerful and flexible way to work with structured data in Python. They offer various methods for data manipulation, analysis, and visualization, making them indispensable tools for data scientists and analysts. With libraries like Pandas, working with DataFrames becomes even more convenient and efficient.

Combinations of Data Structures:

Data structures can also be combined, however not all combinations are possible. 

Table: Possible Combinations

ListsTuplesDictionariesSetsDataFrames
ListsYesYesYesNoNo
TuplesYesYesYesNoNo
DictionariesYesYesYesNoNo
SetsNoNoNoYesNo
DataFramesNoNoNoNoYes

Explanation:

  • Lists of lists, tuples, dictionaries: Possible because lists can contain these data structures.

  • Tuples of lists, tuples, dictionaries: Possible because tuples can contain these data structures.

  • Dictionaries of lists, tuples, dictionaries: Possible because dictionaries can contain these data structures.

  • Sets of lists, tuples, dictionaries: Not possible because sets cannot contain mutable objects like lists and dictionaries.

  • DataFrames of lists, tuples, dictionaries: Not applicable because DataFrames cannot directly contain these data structures.

  • Sets: Exceptional in terms of containing other collections due to immutability and uniqueness properties.

  • DataFrames: Exceptional in terms of being a specialized two-dimensional labeled data structure.

Conclusion

In this series, we've explored some of the most commonly used data structures in Python: Lists, Tuples, Dictionaries, Sets, and DataFrames. Each of these data structures has its own characteristics, use cases, and advantages, making them valuable tools for various programming tasks.

Lists and Tuples are versatile collections that can store multiple elements of different types, with Tuples offering immutability compared to the mutable nature of Lists. Dictionaries provide a convenient way to store key-value pairs, enabling fast lookup based on keys. Sets offer unordered collections of unique elements, useful for tasks that require membership testing or eliminating duplicates. DataFrames, on the other hand, are specialized two-dimensional labeled data structures commonly used for data manipulation and analysis tasks.

By understanding these data structures and their properties, Python programmers can effectively organize and manipulate data to achieve their desired outcomes. Whether you're working on simple scripting tasks, data analysis projects, or complex machine learning algorithms, having a strong understanding of these data structures is essential for writing efficient and maintainable code.

Continue to explore and experiment with these data structures in your Python projects to gain a deeper understanding of their capabilities and learn how to leverage them effectively to solve real-world problems.

Thursday, April 25, 2024

Exploring Different Methods to Display Images in Python - Part 1

When working with images in Python, there are various libraries and frameworks available, each with its own strengths and capabilities. In this series, we'll explore different methods to display images.
This first post is about using popular libraries such as Matplotlib, OpenCV, Pygame, Pillow (PIL), and Tkinter.

Ilustration for this blogpost created using NightCafe Studio.

**Note:** The scripts for each method are available on [GitHub](https://github.com/JanJeronimus/Python_Show_Image), and they have been tested on a Windows 10 machine.

1. Matplotlib

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. While its primary use is for plotting graphs and charts, it also provides functionalities for displaying images.

2. OpenCV

OpenCV (Open Source Computer Vision Library) is a powerful open-source computer vision and machine learning software library. It's widely used for real-time image processing and computer vision tasks.

3. Pygame

Pygame is a cross-platform set of Python modules designed for writing video games. It provides functionalities for multimedia applications, including displaying images and handling user input.

4. Pillow (PIL)

Pillow, also known as PIL (Python Imaging Library), is a library for opening, manipulating, and saving many different image file formats. It's widely used for basic image processing tasks.

5. Tkinter

Tkinter is the standard GUI (Graphical User Interface) toolkit for Python. It provides a simple way to create GUI applications, including the display of images. My script displays an image using the Tkinter library with the help of Pillow (PIL).

Conclusion :

My conclusion after having explored this five different methods for displaying images in Python: Matplotlib, OpenCV, Pygame, Pillow (PIL), and Tkinter. Each method has its advantages and considerations. Matplotlib provides a straightforward approach, while OpenCV may require additional setup time but offers powerful image processing capabilities. Pygame, while versatile, may exhibit slower image display performance. Pillow offers simplicity for basic image handling tasks, and Tkinter provides a GUI-based solution. Depending on the specific requirements of a project, developers can choose the most suitable method to efficiently display images while considering factors such as ease of use, performance, and required functionalities.

Stay tuned for more insights and explorations in the upcoming parts of this series!

Additionally, Also explore my Image Viewer Repository: Another Python Tkinter Project. This collection of image viewer applications is developed using the Tkinter library for GUI and the PIL module for image handling. Each version of the image viewer offers unique functionalities and enhancements, catering to different user preferences and needs. You can find more about it here.


Sunday, April 21, 2024

Exploring my Image Viewer Repository: A Python Tkinter Project (Part 2)

Are you interested in exploring the world of Python GUI programming and image manipulation? If so, you're in the right place! In this blog post, we'll dive further into creating a simple yet powerful picture viewer application using Python's Tkinter library. 

A short time ago a first post about this topic was presented on my blog. and i already have planned a next post about this topic with further improvements. 

Introduction to Tkinter and Image Manipulation

Tkinter is a popular Python library for creating graphical user interfaces (GUIs). It provides a simple and intuitive way to build interactive applications with widgets like buttons, labels, and frames.

Combined with the PIL (Python Imaging Library) or its successor, Pillow, Tkinter becomes a versatile tool for handling and displaying images within your applications. With these libraries, you can load, resize, and manipulate images with ease.

Coding and Tkinter libary (create using NightCafe Studio AI)

Building the Picture Viewer App

The goal is to create a picture viewer application that allows users to view different images and toggle the visibility of the picture frame. Here's an overview of the key components of our application:

Tkinter Window Initialization: We start by creating a Tkinter window as the main container for our application.

Picture Frame Creation: Within the main window, we create a frame to display the images. This frame will dynamically update to show the selected image.

Menu Bar Setup: We design a menu bar with options to control the picture frame. Users can show or hide the frame, toggle its visibility, and exit the application.

Image Loading and Display: Using PIL (or Pillow), we load images from file paths and display them within the picture frame. Images are resized to fit the frame's dimensions.

Frame Control Functions: We implement functions to handle frame visibility. Users can show, hide, or toggle the frame's visibility based on their preferences.

Exploring the Code

The Python code is structured into a class named PictureViewerApp, encapsulating the entire application logic. Here's a brief breakdown of the class methods:

  • __init__: Initializes the Tkinter window, creates the picture frame, loads an initial image, and sets up the menu bar.
  • create_menu: Creates the menu bar with options for controlling the picture frame and selecting images.
  • load_image: Loads an image file from the provided path and displays it within the picture frame.
  • display_image: Displays the currently loaded image within the picture frame after resizing it to fit.
  • show_frame and hide_frame: Functions to explicitly show or hide the picture frame.
  • toggle_frame: Toggles the visibility of the picture frame based on its current state.

In the provided code, the lambda function is used within the menu creation to bind commands to menu items dynamically. Let's break down its use and why it's needed in this context.   

The most recent version of the code will be posted as  `image_viewer05_lambda.py` in my GitHub Repository about this topic however i also did put the code below:   

import tkinter as tk

from PIL import ImageTk, Image

class PictureViewerApp:

    """

    A simple picture viewer application using Tkinter.

    This application allows users to view different pictures and toggle the visibility of the picture frame.

    Attributes:

        master (tk.Tk): The main Tkinter window.

        plugin_frame (tk.Frame): The frame to display the pictures.

        current_image (Image): The currently displayed image.

        menu_bar (tk.Menu): The main menu bar.

        frame_menu (tk.Menu): Submenu for frame options.

        picture_menu (tk.Menu): Submenu for picture options.

    """

    def __init__(self, master):

        """

        Initialize the PictureViewerApp.

        Args:

            master (tk.Tk): The main Tkinter window.

        """

        self.master = master

        master.title("Picture Viewer Example")

        # Create a frame inside the main window

        self.plugin_frame = tk.Frame(master, padx=20, pady=20)

        self.plugin_frame.pack()

        # Load initial image

        self.current_image = Image.open("img/picture1.jpg")

        self.display_image()

        # Create menu

        self.create_menu()

    def create_menu(self):

        """

        Create the main menu bar and its submenus.

        """

        self.menu_bar = tk.Menu(self.master)

        self.master.config(menu=self.menu_bar)

        # Frame submenu

        self.frame_menu = tk.Menu(self.menu_bar, tearoff=0)

        self.frame_menu.add_command(label="Show", command=self.show_frame)

        self.frame_menu.add_command(label="Hide", command=self.hide_frame)

        self.frame_menu.add_separator()

        self.frame_menu.add_command(label="Toggle", command=self.toggle_frame)

        self.frame_menu.add_separator()

        self.frame_menu.add_command(label="Exit", command=exit)

        # Pictures submenu

        self.picture_menu = tk.Menu(self.menu_bar, tearoff=0)

        self.picture_menu.add_command(label="Picture 1", command=lambda: self.load_image("img/picture1.jpg"))

        self.picture_menu.add_command(label="Picture 2", command=lambda: self.load_image("img/picture2.jpg"))

        self.picture_menu.add_command(label="Picture 3", command=lambda: self.load_image("img/picture3.jpg"))

        self.picture_menu.add_command(label="Picture 4", command=lambda: self.load_image("img/picture4.jpg"))

        self.picture_menu.add_command(label="Picture 5", command=lambda: self.load_image("img/picture5.jpg"))

        self.menu_bar.add_cascade(label="Frame", menu=self.frame_menu)

        self.menu_bar.add_cascade(label="Pictures", menu=self.picture_menu)

    def load_image(self, filename):

        """

        Load an image file and display it in the frame.

        Args:

            filename (str): The path to the image file.

        """

        self.current_image = Image.open(filename)

        self.display_image()

    def display_image(self):

        """

        Display the current image in the frame.

        """

        # Clear the frame

        for widget in self.plugin_frame.winfo_children():

            widget.destroy()

        # Resize the image to fit the frame

        resized_image = self.current_image.resize((400, 300), Image.BILINEAR)

        photo = ImageTk.PhotoImage(resized_image)

        # Display the image in a label

        image_label = tk.Label(self.plugin_frame, image=photo)

        image_label.image = photo  # Keep a reference to avoid garbage collection

        image_label.pack()

    def show_frame(self):

        """

        Show the picture frame.

        """

        self.plugin_frame.pack()

    def hide_frame(self):

        """

        Hide the picture frame.

        """

        self.plugin_frame.pack_forget()

    def toggle_frame(self):

        """

        Toggle the visibility of the picture frame.

        """

        if self.plugin_frame.winfo_ismapped():

            self.hide_frame()

        else:

            self.show_frame()


# Create the main window and run the application

root = tk.Tk()

app = PictureViewerApp(root)

root.mainloop()


What is a Lambda Function?

A lambda function in Python is a small anonymous function defined using the lambda keyword. It allows you to create a function without a name. Lambda functions can have any number of arguments but only one expression, which is evaluated and returned. They are often used as a shortcut for simple, one-line functions.

Why is Lambda Needed?

In the context of the provided code, lambda functions are used to create anonymous functions that call the load_image method with different arguments based on the selected menu item. Let's take a closer look at how this is achieved:

self.picture_menu.add_command(label="Picture 1", command=lambda: self.load_image("img/picture1.jpg"))

Here, lambda: self.load_image("img/picture1.jpg") is a lambda function. When the "Picture 1" menu item is selected, this lambda function is executed, which in turn calls the load_image method with the argument "img/picture1.jpg". Similarly, lambda functions are used for other menu items, each calling the load_image method with a different file path.

Why Lambda is Useful:

Dynamic Binding: Lambda functions allow us to bind commands to menu items dynamically. Instead of defining a separate function for each menu item, we can use lambda to create anonymous functions inline.

Conciseness: Lambda functions are concise and can be written in a single line, making the code more readable and reducing the need for additional named functions.

Flexibility: Lambda functions are flexible and can be used in situations where a named function would be cumbersome or unnecessary, such as when defining callbacks for GUI events.

Conclusion

By combining the power of Tkinter for GUI development and PIL/Pillow for image manipulation, we've created a functional picture viewer application in Python. This project serves as a great starting point for exploring more advanced GUI applications and image processing tasks.

The lambda functions are useful in this context because they provide a concise and flexible way to dynamically bind commands to menu items, allowing for cleaner and more readable code. They help streamline the process of defining callbacks for GUI elements like menu items.

In a an upcoming part i will further improve this program. Whether you're building a simple viewer for personal use or integrating image viewing capabilities into a larger application, Tkinter and PIL/Pillow provide the tools you need to succeed.

Happy coding and exploring the world of Python GUI programming!

Friday, April 19, 2024

ChatGPTtrainer

I asked ChatGPT (GPT-3.5 model chat.openai.com on 17apr2024): "What is the length of text i can type in here?"
The response was: "You can type up to 4096 characters in a single message. If you need to convey more information, you can break it up into multiple messages."

So i created with help of ChatGTP a tool to split information in digestible parts of around 4000 characters in separate files and published it on GitHub https://github.com/JanJeronimus/ChatGPTtrainer

Saturday, April 6, 2024

Emoji

Exploring Emojis in Python: A Fun Demo

Emojis have become an integral part of online communication, adding color and emotion to our text-based conversations. Did you know that you can also use emojis as variables in your Python code? In this post, we'll explore how to do just that with a simple Python script.

Using Emojis as Variables

I recently stumbled upon a fascinating aspect of Python: you can use emojis as variable names and also print out the variable name along with its value. This opens up a world of possibilities for adding a touch of fun to your code. 

Let's take a look at a Python script I created to demonstrate this concept. The script contains various emoji variables along with their Unicode representations. It also includes a function called show_line() that prints each emoji variable, its Unicode representation, and its description.

Here's a snippet of the script: .

# Emoticons
emoji_smile = '\U0001F600'               # 😀
emoji_scissors = '\u2702'                # ✂
emoji_check = '\u2714'                   # ✔
# More emoji variables ...


def show_line(var_name) -> None:
    if not isinstance(var_name, str):
        print("Error: var_name must be a string.")
        return
    global_vars = globals()
    if var_name in global_vars:
        var_value = global_vars[var_name]
        var_suffix = var_name.replace("emoji_", "")
        print(f"{var_name.ljust(40)} = '", end="")
        var_unicode_hex = ''.join([f"\\U{hex(ord(char))[2:].upper().zfill(8)}" for char in var_value])
        print(var_unicode_hex, end="'\t# ")
        print(f"{var_value}, '{var_suffix}'")
    else:
        print(f"Error: {var_name} not found in global variables.")

# Demo usage of the script
print("\n# Emoticons:")
show_line('emoji_smile')
show_line('emoji_scissors')
# More calls to show_line() ...

How to Use the Script

To run the script and see the emojis in action, simply execute the main() function of the full script in my GitHub. You'll see each emoji variable printed along with its Unicode representation and description.

Additional Information

This script is intended for simple use cases when only a few emojis are used. For more advanced emoji usage, you might want to consider using the python-emoji library.

Feel free to explore my GitHub repository for the complete script and contribute if you'd like to  improve the script further.



Friday, April 5, 2024

Exploring my Image Viewer Repository: A Python Tkinter Project (Part 1)

Introduction:

Welcome to my Image Viewer Repository! This GitHub repository hosts a collection of image viewer applications developed in Python using the Tkinter library for GUI and the PIL module for image handling. Each version of the image viewer offers unique functionalities and enhancements, catering to different user preferences and needs.

Repository Overview:

  • image_viewer_basic.py: This version of the image viewer provides a basic interface with buttons to load predefined images.
  • image_viewer_dropdown.py: An enhanced version featuring a dropdown menu to select images, offering a more intuitive user experience.
  • image_viewer_with_menu.py: This version introduces a menu-based interface for selecting images, adding another layer of usability to the application.
  • image_viewer_img_objects.py: An advanced iteration of the image viewer where images are treated as objects, allowing for more flexibility and scalability in managing and displaying images.

Usage:

To run any of the provided Python scripts, follow these simple steps:

  1. Clone or download the repository to your local machine.
  2. Open a terminal or command prompt.
  3. Navigate to the directory containing the desired Python script.
  4. Run the following command: python script_name.py, replacing script_name.py with the name of the script you wish to execute.

License:

This project is licensed under the MIT License, granting users the freedom to utilize, modify, and distribute the code as they see fit. For more details, refer to the LICENSE file in the repository.

Explore the Repository:

Ready to dive into the world of image viewers? Visit my Image Viewer Repository on GitHub to access the code and explore the different versions of the image viewer: Image Viewer Repository

Conclusion:

Thank you for exploring my Image Viewer Repository! Whether you're a Python enthusiast, a Tkinter aficionado, or simply looking for an intuitive way to view images, this repository has something for everyone. Feel free to experiment with the different versions and make the image viewer your own. Happy coding!

Thursday, March 28, 2024

Python pandas *.csv import and export differences

As i am working on a project involving *.csv data files using the Python programming language and pandas a march 2024 blogpost about this topic. The data gets imported in Python pandas dataframes and later also saved to *.csv files. I hope to post later more details about the resulting program (I also have plans to post the final project on my GitHub)  
When checking details i noticed differences between the imported and exported data. When reading files and writing them back i immediately noticed the difference in file length. Recognizing the problem (more about them later) was not extreme difficult.

Python pandas
Python pandas

Illustration made with help of  NightCafe AI Art Creator

Solving the issue did cost more time. I wasted a lot of time with trying the solutions provided by ChatGTP, giving feedback about the problems however it did not solve my problem. By searching on internet i learned i was not the only one with the problem. However finding a solution was more difficult. In fact there where two problems in the *.csv

Missing double quotes ""

All data in the *.csv file where strings surrounded by double quotes " . When writing the *.csv file back the double quotes where gone.

Solution: When writing using the to_csv() use the option    quoting=csv.QUOTE_ALL 

NaN (or Null) values

The *.csv file contained items as "" and "None" . During reading of the data all both these values are converted to NaN in the Python panda dataframes. NaN ( in databases known as Null ) values are missing or not assigned values. 
For my project i needed to keep "" and "None" when writing back the data. Solutions provided mostly changed both values to "" or "None".  ChatGPT could not help me, however it (or he?) knew the answer.  When entered the solution that i found the response was the explanation of my solution. 

Solution: When reading using read_csv() use the option     keep_default_na=False

From the documentation on  https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html  :
By default the following values are interpreted as NaN: “ “, “#N/A”, “#N/A N/A”, “#NA”, “-1.#IND”, “-1.#QNAN”, “-NaN”, “-nan”, “1.#IND”, “1.#QNAN”, “<NA>”, “N/A”, “NA”, “NULL”, “NaN”, “None”, “n/a”, “nan”, “null “.

ChatGPT provided only solutions with the na_values options, However if keep_default_na is True, and na_values are specified, na_values is appended to the default NaN values used for parsing.

The final code

Important parts of Python ( pandas ) code used

import pandas as pd

my_import_df = pd.read_csv(csv_import_file, encoding='latin-1', keep_default_na=False, dtype=object)

my_export_df.to_csv( csv_export_file, quoting=csv.QUOTE_ALL, index=False)

Hoping to post something about my first pre-release version with some first functionalities of my project soon.