用於數據處理和分析。它提供了兩種主要的數據結構,即DataFrame(類似於表格)和Series(類似於一維數組)。Pandas允許您輕鬆地讀取、處理和分析各種數據,包括CSV文件、Excel文件、SQL數據庫等。
import pandas as pd
grades = {
"name": ["David", "Melvin", "Romain", "Ricky"],
"math": [80, 75, 77, 86],
"chinese": [65, 90, 85, 70]
}
df = pd.DataFrame(grades)
print("使用字典來建立df:")
print(df)
print("=====================")
grades = [
["David", 80, 65],
["Melvin", 75, 90],
["Romain", 77, 85],
["Ricky", 86, 70]
]
new_df = pd.DataFrame(grades)
print("使用陣列來建立df:")
print(new_df)
import pandas as pd
grades = {
"name": ["David", "Melvin", "Romain", "Ricky"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
print("原來的df")
print(df)
print("=================================")
new_df = df.head(2)
print("取得最前面的兩筆資料")
print(new_df)
import pandas as pd
cars = ["BMW", "BENZ", "Toyota", "Nissan", "Lexus"]
select = pd.Series(cars)
print(select)
import pandas as pd
dict = {
"factory": "Taichung",
"sensor1": "1",
"sensor2": "2",
"sensor3": "3",
"sensor4": "4",
"sensor5": "5"
}
select = pd.Series(dict, index = dict.keys()) # 排序與原 dict 相同
print(select[0])
print("=====")
print(select['sensor1'])
print("=====")
print(select[[0, 2, 4]])
print("=====")
print(select[['factory', 'sensor1', 'sensor3']])
import pandas as pd
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
df.index = ["s1", "s2", "s3", "s4"] #自訂索引值
df.columns = ["student_name", "math_score", "chinese_score"] #自訂欄位名稱
print(df)