按列值分组并横向全连接
原效果
处理效果
import pandas as pd
def segmentation_col(df ,col_name):
# 按列的值分组
list_type = df[col_name].unique()
df_list = []
for item in list_type:
df_list.append(df[df[col_name] == item])
# 并横向连接
# 判断是否能连接
if len(df_list) == 0:
exit()
df0 = df_list[0].copy()
for i in range(1, len(df_list)):
df0 = df0.reset_index(drop=True)
df_list[i] = df_list[i].reset_index(drop=True)
# 赋值重置索引
# df0.index = pd.Series(range(0, len(df0)))
# df_list[i].index = pd.Series(range(0, len(df_list[i])))
df0 = pd.concat([df0, df_list[i]], axis=1).copy()
print(df0)
return df0
if __name__ == '__main__':
# 创建一个示例DataFrame
df = pd.DataFrame({
'group': ['A', 'A', 'B', 'B', 'A', 'B', 'A', 'B'],
'value': [1, 2, 3, 4, 5, 6, 7, 8]
})
col_name = 'group'
df0 = segmentation_col(df, col_name)
print(df0)
#rint(result)