python使用pandas处理dataFrame

原有的DataFrame

img


想转换为

img

想按照原有的dataFrame中的名称、时间和模式进行统计,将相同名称、时间相同及模式相同的数据进行统计并在表后添加列进行展示。

大概过程如下
分组统计后,转成字典-列表-Dataframe

img


import pandas as pd
# 初始化数据
data_str = '''Col1,Col2,Col3,Col4
A,2021/1/12,AA,1
A,2021/1/12,AA,1
D,2021/1/13,AA,1
A,2021/1/12,FF,0
B,2021/1/12,FF,0
C,2021/1/12,AA,4
C,2021/1/12,FF,1
C,2021/1/12,FF,0
D,2021/1/12,AA,0'''

lst = [n.split(",") for n in  data_str.split()]
df1 = pd.DataFrame(lst[1:])
df1.columns =  lst[0]
df2 = df1.groupby(['Col1','Col2','Col3']).count()


# 处理过程
lst_dict = {}
for d in df2.iterrows():
    temp = list(d[0])
    temp_key = str(temp[:2])
    if temp_key in lst_dict:
        temp_item = lst_dict[temp_key]
        temp_item[temp[2]] = d[1][0]
    else:
        lst_dict[temp_key] = {temp[2]:d[1][0]}
# print(lst_dict)
lst_2 = []
for d in lst_dict:
    items = eval(d)
    data = lst_dict[d]
    items.append(data['AA'] if 'AA' in data else 0 )
    items.append(data['FF'] if 'FF' in data else 0)
    lst_2.append(items)
# print(lst_2)
df3 = pd.DataFrame(lst_2)
df3.columns =  ['Col1','Col2',' AA模式计数','FF模式计数']

print(df3)