# Read from CSV
= pd.read_csv('data.csv')
df
# Read from XLS
= pd.read_excel('data.xlsx') df
DataFrames
A DataFrame is essentially a two-dimensional, labeled data structure with columns of potentially different types, similar to a spreadsheet (Excel) or table.
It is a widely used structure in the data manipulation Python library called
pandas
.You can read CSV, XLS and many other files and store them in a DataFrame object. For example:
- You can check documentation for these functions here
Some operations
- You can view the top or bottom rows of a DataFrame using
head()
andtail()
methods.
print(df.head()) # View the first 5 rows
print(df.tail()) # View the last 5 rows
- You can access columns and rows of a DataFrame using indexing and slicing.
print(df['Name']) # Access a column
print(df.iloc[0]) # Access a row by index
- You can perform basic operations like filtering, sorting, and adding columns.
# Filter rows
= df[df['Age'] > 30]
filtered_df
# Sort by a column
= df.sort_values(by='Age', ascending=False)
sorted_df
# Add a new column
'IsAdult'] = df['Age'] > 18 df[
Example: reading a CSV file with Pokémon Cards data and creating a GUI
The data file can be downloaded here.
import pandas as pd
from guizero import App,ListBox,Text
def set_text():
= cards_lb.value
t += '\nType: '+ str(cards[cards['name']==cards_lb.value]['types'].values[0])
t += '\nHP =: ' + str(cards[cards['name']==cards_lb.value]['hp'].values[0])
t = t
text.value
= pd.read_csv("pokemon-tcg-data.csv")
cards = cards[cards['set']=='Jungle'][:100] # filtering only by one set
cards
= App(title="Pokémon Cards")
app = ListBox(app, height='fill', align='left', width=100,
cards_lb =list(cards['name']),
items= True,
scrollbar =set_text)
command= Text(app, height='fill', width='fill', align='right')
text
app.display()