Python 数据帧转换为新格式的有效方法
我目前正在使用现有的数据帧制作新的数据帧 假设我们有如下所示的dataframePython 数据帧转换为新格式的有效方法,python,pandas,Python,Pandas,我目前正在使用现有的数据帧制作新的数据帧 假设我们有如下所示的dataframe tt2 = pd.DataFrame(columns=['test','class']) test = [1,2,3,4,1,2,3,4,4] test_class = ['a','b','c','d','b','c','a','d','a'] tt2['test'] = test tt2['class'] = test_class test class 0 1 a 1 2
tt2 = pd.DataFrame(columns=['test','class'])
test = [1,2,3,4,1,2,3,4,4]
test_class = ['a','b','c','d','b','c','a','d','a']
tt2['test'] = test
tt2['class'] = test_class
test class
0 1 a
1 2 b
2 3 c
3 4 d
4 1 b
5 2 c
6 3 a
7 4 d
8 4 a
然后,我想将这个结构转换为
test class1 class2 class3
1 a b
2 b c
3 c a
4 d d a
因此,我们根据唯一键值的最大元素数生成新列。这里“4”有3个类,所以我们创建了3个新索引
然后像堆栈一样填充数字
我尝试过使用groupby方法。但是仍然不知道如何正确转换。这对你有用吗 使用groupby和apply,然后使用series string方法和expand设置:
tt2 = pd.DataFrame(columns=['test','class'])
test = [1,2,3,4,1,2,3,4,4]
test_class = ['a','b','c','d','b','c','a','d','a']
tt2['test'] = test
tt2['class'] = test_class
result_df. = tt2.groupby('test').apply(lambda x: "-".join(x['class'])).str.split('-', expand=True)
result_df.columns = ['class' + str(int(col)+1) for col in result_df.columns]
print result_df
给
class1 class2 class3
test
1 a b None
2 b c None
3 c a None
4 d d a