What a dataframe is and why you need one

A dataframe is a table of data in Python — rows and columns, like a spreadsheet. The most common way to create one is with the pandas library, which gives you tools to organize, filter, and analyze data quickly. If you work with data files, databases, or anything that needs sorting and calculation, you will use dataframes constantly.

Pandas is not built into Python by default, so you need to install it first. Open your terminal or command prompt and type: pip install pandas. Once that finishes, you can import pandas into any Python script with import pandas as pd at the top of your file.

Key Takeaways

  • Install pandas with pip install pandas, then import it in your script with import pandas as pd.
  • Create a dataframe from a dictionary using pd.DataFrame(), where each key becomes a column name and each value becomes the column data.
  • Read data directly from a CSV file with pd.read_csv('filename.csv') instead of typing it manually.
  • Access and inspect your dataframe with .head() to see the first few rows, .shape to see dimensions, and .info() to see data types.
  • Add or modify columns by assigning new data to a column name, like df['new_column'] = [values].

Creating a dataframe from a dictionary

The simplest way to build a dataframe is from a Python dictionary. Each key in the dictionary becomes a column name, and the values become the data in that column. Here is the basic pattern:

import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'London', 'Paris']} df = pd.DataFrame(data) print(df)

When you run this, you get a table with three columns (Name, Age, City) and three rows of data. Each list in the dictionary must have the same length, or pandas will throw an error. If your lists are different lengths, pandas cannot line them up into rows.

The variable df now holds your dataframe. You can print it, filter it, do math on it, or save it to a file. This is the foundation for everything else you will do with data in Python.

Reading data from a CSV file

Most of the time, your data already exists in a file. The easiest source is a CSV file (comma-separated values) — the format Excel and Google Sheets use when you export. Pandas can read it in one line:

import pandas as pd df = pd.read_csv('sales_data.csv')

Replace 'sales_data.csv' with the actual path to your file. If the file is in the same folder as your Python script, just use the filename. If it is in a subfolder, use 'data/sales_data.csv'. If it is somewhere else on your computer, use the full path.

Pandas automatically treats the first row as column headers. If your CSV does not have headers, add header=None to tell pandas to number the columns instead: pd.read_csv('file.csv', header=None). You can also read from other formats — Excel files use pd.read_excel(), and databases use pd.read_sql().

Inspecting your dataframe

Once you have created or loaded a dataframe, you need to see what is actually in it. Use these commands to understand your data:

df.head() shows the first five rows. Add a number in parentheses to see more or fewer: df.head(10) shows the first ten rows. df.shape tells you the dimensions — it returns a tuple like (100, 5), meaning 100 rows and 5 columns. df.info() lists every column, its data type (text, number, date), and how many non-empty values it has. df.describe() shows statistics like mean, minimum, and maximum for numeric columns.

These commands are not changing your data — they are just showing you what you have. Use them first whenever you load new data, because surprises (missing values, wrong data types, unexpected columns) show up immediately.

Adding and modifying columns

After you create a dataframe, you often need to add new columns or change existing ones. To add a column, assign a list or series of values to a new column name:

df['Salary'] = [50000, 60000, 75000]

The new column appears at the right end of the dataframe. The list you assign must have the same number of values as your dataframe has rows. If you assign a single value instead of a list, pandas copies that value to every row: df['Country'] = 'USA' adds a Country column with 'USA' in every cell.

To modify an existing column, assign new values the same way: df['Age'] = df['Age'] + 1 adds one year to every age. You can also use functions to transform data — for example, df['Name'] = df['Name'].str.upper() converts all names to uppercase. To remove a column, use df.drop('ColumnName', axis=1).

Working with different data types

Dataframes can hold different kinds of data in different columns: text (strings), whole numbers (integers), decimals (floats), dates, and more. When you create a dataframe from a dictionary or CSV, pandas guesses the type based on what it sees. Usually it guesses right, but sometimes it gets it wrong.

Check what type each column is with df.info(). If a column is the wrong type, convert it with df['ColumnName'] = df['ColumnName'].astype(int) for integers, .astype(float) for decimals, or pd.to_datetime(df['ColumnName']) for dates. Converting a text column to a number fails if any cell contains non-numeric text, so check your data first with df.head().

Dates are especially important because pandas handles them specially — you can filter by date ranges, extract the month or year, or calculate time differences. When you load a CSV, pandas does not automatically recognize dates, so you often need to tell it which columns are dates: pd.read_csv('file.csv', parse_dates=['DateColumn']).

Saving your dataframe to a file

Once you have created or modified a dataframe, you usually want to save it. The most common format is CSV:

df.to_csv('output.csv', index=False)

The index=False tells pandas not to save the row numbers as a separate column — you almost always want this. If you omit it, your CSV will have an extra column of numbers on the left. To save as Excel instead, use df.to_excel('output.xlsx'). You can also save to JSON, SQL databases, or many other formats using to_json(), to_sql(), and similar methods.

When you save, the file goes in the same folder as your Python script unless you specify a different path. Check that the file actually appeared before you close your script — if pandas hits an error (like a file already open in Excel), it will fail silently in some cases.

Frequently Asked Questions

What is the difference between a list and a dataframe?

A list is a simple sequence of items in Python. A dataframe is a table with rows and columns, like a spreadsheet. Dataframes are much better for data analysis because you can filter by column, do math across rows, and work with labeled data instead of just positions.

Do I have to install pandas, or does Python come with it?

Pandas does not come with Python by default. You must install it once using pip install pandas. After that, any Python script on your computer can use it by importing with import pandas as pd. You only install once per computer.

What happens if my CSV file has missing values?

Pandas reads missing values as NaN (not a number). You can see where they are with df.isnull(), which returns True for empty cells. To remove rows with missing values, use df.dropna(). To fill them with a specific value, use df.fillna(0) or df.fillna('Unknown').

Can I create a dataframe with no data and add rows later?

Yes. Create an empty dataframe with column names using df = pd.DataFrame(columns=['Name', 'Age', 'City']). Then add rows with df = pd.concat([df, pd.DataFrame([{'Name': 'Alice', 'Age': 25, 'City': 'New York'}])], ignore_index=True). This is slower than building all your data at once, so avoid it for large datasets.

How do I filter a dataframe to show only certain rows?

Use square brackets with a condition: df[df['Age'] > 30] shows only rows where Age is greater than 30. You can combine conditions with & (and) or | (or): df[(df['Age'] > 30) & (df['City'] == 'New York')] shows rows where Age is over 30 AND City is New York.