保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Data Science

The Absolute Beginner’s Guide to Pandas DataFrames

Learn how to initialize dataframes from dictionaries, lists, and NumPy arrays Ibrahim Salami November 17, 20255 min read Image by author Coming from a SQL background, learning Python for data analysis has been a bit challenging. The syntax is simpler — true. However, the language and terminology are completely different. In SQL, you’ll have to interact with databases, tables and columns. In Python, however, for data analysis, your bread and butter is going to be data structures. Data structures in Python are like data storage objects. Python includes several built-in data structures, such as lists, tuples, sets, and dictionaries. All these are used to store and manipulate data. Some are mutable (lists) and some are not (tuples). To learn more about Python data structures, I highly recommend reading the book "Python for Data Analysis" by Wes McKinney. I just started reading it, and I think it’s stellar. In this article, I’m going to walk you through what a DataFrame is in Pandas and how to create one step by step.

Understand Array fundamentals

There’s a library in Python called NumPy; you might have heard of it. It’s mostly used for mathematical and numerical computations. One of the features it offers is the ability to create arrays. You might be wondering. What the heck is an Array? Learn this step by step with the interactive AI and Data Scientist roadmap. An array is similar to a list, except it only stores values of the same data type. Lists, however, can store values of different data types (int, text, boolean, etc). Here’s an example of a list python

my_list = [1, “hello”, 3.14, True]

Lists are also mutable. In other words, you can add and remove elements. Back to arrays. In Numpy, Arrays can be multidimensional — this is called ndarrays (N-dimensional arrays). For instance, let’s import the Numpy library in Python.

python

import numpy as np

To create a basic array in Numpy, we use the np.array() function. In this function, our array is stored. python

arr = np.array([1, 2, 3, 4, 5])
arr

Here’s the result: python

array([1, 2, 3, 4, 5])

To check the data type. python

type(arr)

We’ll get the data type. python

numpy.ndarray

The cool thing about arrays is that you can perform mathematical calculations on them. For instance python

arr*2

The result: python

array([ 2, 4, 6, 8, 10])

Pretty cool, right? Now that you know the basics of arrays in Numpy. Let’s dig deeper into N-dimensional arrays. The array you see above is a 1-dimensional (1D) array. Also known as vector arrays, 1D arrays consist of a sequence of values. Like so, [1,2,3,4,5] 2-dimensional arrays (Matrix) can store 1D arrays as the values. Similar to rows of a table in SQL, each 1D array is like one row of data. The output is like a grid of values. For instance: python

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr

Output: markup

[[1 2 3][4 5 6]]

3-dimensional arrays (Tensors) can store 2D arrays (matrices). For instance, python

import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
arr

Output: markup

[[[1 2 3][4 5 6]][[1 2 3][4 5 6]]]

An array can have an infinite number of dimensions, depending on the amount of data you want to store.

Creating a dataframe from an array

Now that you’ve gotten the gist about Arrays. Let’s create a DataFrame from one. First, we’ll have to import the pandas and NumPy libraries python

import pandas as pd
import numpy as np

Next, create our Array: python

data = np.array([[1, 4], [2, 5], [3, 6]])

Here, I’ve created a 2D Array. Pandas DataFrame can only store 1D and 2D arrays. If you try to pass in a 3D Array, you’ll get an error. Now that we’ve got our Array. Let’s pass it into our DataFrame. To create a DataFrame, use the pd.DataFrame() function. python

# creating the DataFrame
df = pd.DataFrame(data)

# showing the DataFrame
df

Output markup

0 10 1 41 2 52 3 6

Looking good so far. But it needs a little formatting: python

# creating a dataframe
df = pd.DataFrame(data, index=['row1', 'row2', 'row3'],
columns=['col1', 'col2'])

# showing the dataframe
df

Output markup

col1 col2row1 1 4row2 2 5row3 3 6

Now that’s better. All I did was rename the rows using the index attribute and the columns using the columns attribute. And there you go, you have your DataFrame. It’s that simple. Let’s explore some more handy ways to create a DataFrame.

Creating a DataFrame from a dictionary

One of the built-in data structures Python offers is dictionaries. Basically, dictionaries are used to store key-value pairs, where all keys must be unique and immutable. It’s represented by curly brackets {}. Here’s an example of a dictionary: dict = {"name": "John", "age": 30} Here, the keys are name and age, and the values are Alice and 30. Simple as that. Now, let’s create a DataFrame from a dictionary. python

names = ["John", "David", "Jane", "Mary"]
age = [30, 27, 35, 23]

First, I created a list to store multiple names and ages: python

dict_names = {'Names': names, 'Age': age}

Next, I stored all the values in a dictionary and created keys for Names and Age. python

# Creating the dataframe
df_names = pd.DataFrame(dict_names)
df_names

Above, we have our DataFrame storing the dictionary we created. Here’s the output below: markup

Names Age0 John 301 David 272 Jane 353 Mary 23

And there we go, we have a DataFrame created from a dictionary.

Creating a DataFrame from a CSV file

This is probably the method you’ll be using the most. It’s common practice to read CSV files in pandas when trying to do data analysis. Similar to how you open spreadsheets in Excel or import data to SQL. In Python, you read CSVs by using the read_csv() function. Here’s an example: python

# reading the csv file
df_exams = pd.read_csv('StudentsPerformance.csv')

In some cases, you’ll have to copy the file path and paste it as: python

pd.read_csv(“C:\data\suppliers lists — Sheet1.csv”)

Output: Image by Author
And there you go!

Wrapping up

Creating DataFrames in pandas might seem complex, but it actually isn’t. In most cases, you’ll probably be reading CSV files anyway. So don’t sweat it. I hope you found this article helpful. Would love to hear your thoughts in the comments. Thanks for reading! Wanna connect? Feel free to say hi on these platforms LinkedIn Twitter YouTube Medium

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

Ibrahim Salami

See all from Ibrahim Salami DataframePandasProgrammingPythonStatistics Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

Pandas for Football Player Value

Programming A Web-Scraping and Pandas Guided Tutorial Stephen Fordham June 1, 20196 min read

Popular Interview Question that Reduced me to SDE-1 from SDE-2 Role

Programming Debounced that Promotion awayyyy!! Vikranth Kanumuru July 26, 20214 min read

Visualize your RAG Data - Evaluate your Retrieval-Augmented Generation System with Ragas

ChatGPT How to use UMAP dimensionality reduction for Embeddings to show multiple evaluation Questions and their relationships to source documents... Markus Stoll March 3, 202413 min read

Embedding Markdown Files in a Streamlit Dashboard

Data Science Simplify Streamlit app code by moving longer static contents to Markdown files. Marcin Kozak May 28, 20246 min read

Demystifying Neural Networks Pt.2

Artificial Intelligence Implementing hidden layers in NN with Python and NumPy Federica Cerina March 10, 20214 min read

How To Change The Order Of DataFrame Columns In Pandas

Programming Changing the column order and moving columns to the front in pandas DataFrames Giorgos Myrianthous August 15, 20214 min read

How to Implement Artificial Intelligence Using scikit-learn

Machine Learning This introduction to power Python tools will have you applying AI in no time Peter Grant August 30, 202110 min read

LossVal Explained: Efficiently Estimate the Importance of Your Training Data

Deep Learning How to Exploit the Loss Function for Efficient Data Valuation Tim Wibiral January 15, 20256 min read

Closing the Gap Between Machine Learning and Business

Artificial Intelligence What would you say it is you do here? Stephanie Kirmer January 13, 20247 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close