实际中遇到的两个问题?
—— Pandas的DataFrame如何按指定list排序
—— Python的条件分支语句switch/case如何实现
基本用法
# 引入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 no consensus (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
df=pd.read_excel(r".\test.xlsx")
display(df)
Pandas的DataFrame按指定list排序来覆盖默认排序
df_1=pd.DataFrame({"itemtype":list(df.ITEMTYPE.unique())})
# 设置成“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
Python的switch/case实现方法
# 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']]
通过以上处理,对数据进行分类分组,便于后续数据分析。