Specify values in DataFrame columns
Specify how you want to organize your DataFrame by columns.
df = pd.DataFrame(
[[1, 2, 3],
[4, 6, 8],
[10, 11, 12]],
index=[1, 2, 3],
columns=['a', 'b', 'c'])
Read and Write to CSV file
Open the CSV file, copy the data, paste it in our Notepad, and save it in the same directory that houses your Python scripts. Use read_csv
function build into Pandas and index it the way we want.
import pandas as pd
data = pd.read_csv('file.csv')
data = pd.read_csv("data.csv", index_col=0)
Read and write to Excel file
Call the read_excel
function to access an Excel file. Pass the name of the Excel file as an argument.
pd.read_excel('file.xlsx')
df.to_excel('dir/myDataFrame.xlsx', sheet_name='Sheet2')
Read and write to SQL Query
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
pd.read_sql("SELECT * FROM my_table;", engine)
pd.read_sql_table('my_table', engine)
pd.read_sql_query("SELECT * FROM my_table;", engine)
(read_sql()
is a convenience wrapper around read_sql_table()
and read_sql_query())
df.to_sql('myDf', engine)
Get the first element of a Series
Since Pandas indexes at 0, call the first element with ser[0]
.
import pandas as pd
df = pd.read_csv
df['Name'].head(10)
# get the first element
ser[0]
Get the first 5 elements of a Series
Use ser[:n]
to get the first n elements of a Series.
import pandas as pd
df = pd.read_csv
df['Name'].head(10)
ser[:5]
Get the last 5 elements in a Series
Use ser[-n:]
to get the last n elements of a Series.
import pandas as pd
df = pd.read_csv
df['Name'].head(10)
ser[-5:]
Select a single value position
df.iloc[[0],[0]] 'Name'
df.iat([0],[0]) 'Name'
Select a single value by label
df.loc[[0], ['Label']] 'Name'
df.at([0], ['Label']) 'Name'