Skip to content

Documentation

Shakibul Islam edited this page Mar 30, 2025 · 3 revisions

cppandas

Introduction

cppandas is a lightweight C++ library for handling tabular data, inspired by Python's pandas. It provides basic functionalities for loading, manipulating, and displaying data from CSV files.

Installation

1. Using Precompiled Library

If you prefer linking against the precompiled static library (libcppandas.a), follow these steps:

  1. Copy cppandas.h to your project's include directory.
  2. Copy libcppandas.a to your project's lib directory.
  3. Compile and link

example g++

g++ main.cpp -o main -Iinclude -Llib -lcppandas

2. Using Source Files

Include cppandas.h and cppandas.cpp in your project:

#include "cppandas.h"

Compile with:

g++ main.cpp cppandas.cpp -o main

Usage

Creating a DataFrame

You can create a DataFrame manually using a map of column names to vectors of values.

std::map<std::string, std::vector<std::string>> data = {
    {"Name", {"Alice", "Bob", "Charlie"}},
    {"Age", {"25", "30", "35"}}
};
DataFrame df(data);
df.show_frame();

Reading from a CSV File

DataFrame df;
df.read_csv("data.csv");
df.show_frame();

Displaying Data

df.head(); // default Show first 5 rows
df.head(10); // Show first 10 rows 

Accessing a Column

std::vector<std::string> ages = df["Age"];

Converting to a Vector

std::vector<std::vector<int>> matrix = df.to_vector<int>({"Age"});

Handling Missing Data

df.dropna();  // Remove rows with NaN values
df.fillna("0");  // Replace NaN values with "0"

Dropping Columns

df.drop_col("Age");
df.drop_col({"Name", "Age"});

API Reference

DataFrame()

  • Default constructor.

DataFrame(std::map<std::string, std::vector<std::string>> data)

  • Constructs a DataFrame from a map of column names to vectors.

void read_csv(const std::string& filename)

  • Loads data from a CSV file.

void head(int n = 5) const

  • Displays the first n rows.

std::vector<std::string> operator[](const std::string& col_name) const

  • Returns the values of a column as a vector.

template<typename type> std::vector<std::vector<type>> to_vector(const std::vector<std::string>& cols)

  • Converts selected columns to a 2D vector of the specified type.

void show_frame() const

  • Prints the entire DataFrame.

void dropna()

  • Removes rows containing NaN values.

void fillna(const std::string& value)

  • Replaces NaN values with a specified value.

void drop_col(std::string label)

  • Removes a column by name.

void drop_col(std::vector<std::string> labels)

  • Removes multiple columns.

void drop_col(std::initializer_list<std::string> labels)

  • Removes multiple columns using an initializer list.

License

cppandas is under the MIT License.