# 引入pandas的數據類型「category」,從而進行排序。
# python中沒有switch case語句。官方的解釋:You can do this easily enough with a sequence of if... elif... elif... else.There have been some proposals for switch statement syntax, but there is noconsensus (yet) on whether and how to do range tests.
https://docs.python.org/2/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python
可用字典方法解決這個問題,具體方法如下:
def function_1(...):
實現過程數據源
...
functions = {'a': function_1,
'b': function_2,
'c': self.method_1, ...}
func = functions[value]
func()import pandas as pd
Pandas的DataFrame按指定list排序來覆蓋默認排序
df=pd.read_excel(r".\test.xlsx")
display(df)df_1=pd.DataFrame({"itemtype":list(df.ITEMTYPE.unique())})
Python的switch/case實現方法
# 設置成「category」數據類型
df_1['itemtype'] = df_1['itemtype'].astype('category')
#情況1:指定的list所包含元素與Dataframe中需要排序的列的元素一致
# list_custom1=["電耗量","動力用電","空調用電"]
# #使用 reorder_categories()方法來實現,inplace = True,使 recorder_categories生效
# df_1['itemtype'].cat.reorder_categories(list_custom, inplace=True)
# # inplace = True,使 df生效
# df_1.sort_values('itemtype', inplace=True)
# 情況2:指定list元素多的情況,一把指定的list所包含元素比Dataframe中需要排序的列的元素多,覆蓋需要排序的所有元素。
#list_custom2=["電耗量","照明插座用電","空調用電","動力用電","特殊用電"]
# 使用 set_categories()方法來實現,inplace = True,使 set_categories生效
df_1['itemtype'].cat.set_categories(list_custom2, inplace=True)
df_1.sort_values('itemtype', ascending=True)
df_1# switch = {"keyA":functionA,"keyB":functionB,"keyC":functionC}
# try:
# switch["value"]() #執行相應的方法。
# except KeyError as e:
# pass
#分支語句
switch = { "電耗量": lambda x:list(x[x.ITEMTYPE=="電耗量"]["NAME"]),
"照明插座用電": lambda x:list(x[x.ITEMTYPE=="照明插座用電"]["NAME"]),
"空調用電": lambda x:list(x[x.ITEMTYPE=="空調用電"]["NAME"]),
"動力用電": lambda x:list(x[x.ITEMTYPE=="動力用電"]["NAME"]),
"特殊用電": lambda x:list(x[x.ITEMTYPE=="特殊用電"]["NAME"])}
#以上等效語句:list(df.loc[df.ITEMTYPE=="電耗量","NAME"])
#存儲數據
fxzl_list=[]
itemtype_list=[]
for i in list(df_1.itemtype):
try:
fxzl_list.append(switch[i](df))
itemtype_list.append(i)
except KeyError as e:
pass
#輸出數據
itemtype_list
fxzl_list['電耗量', '空調用電', '動力用電']
[['支路1', '支路4', '支路16'], ['支路2', '支路3', '支路6', '支路7', '支路8', '支路9', '支路10', '支路11', '支路13', '支路14', '支路15'], ['支路5', '支路12']]
通過以上處理,對數據進行分類分組,便於後續數據分析。