将每个行数据转移到PANDAS DataFrame中每个ID的列数据中



我的pandas datframe看起来像

Id   Length1 height1 Length2 height2
1     100     20       80     30
2      70     10       60     15

所有ID的数据都需要分组为每个测量的长度/高度。

Id   0           1     2       3
1    100         20    70      10
2    80          30    60      15

如何将行中的行转移到列和列中数据框中的行

设置

df = pd.DataFrame(dict(
    Length1=[1, 2, 3],
    Height1=[4, 5, 6],
    Length2=[7, 8, 9],
    Height2=[0, 1, 2]
))['Length1 Height1 Length2 Height2'.split()]
df
   Length1  Height1  Length2  Height2
0        1        4        7        0
1        2        5        8        1
2        3        6        9        2

pd.DataFrame({n: g.values.ravel() for n, g in df.groupby(lambda x: x[-1], 1)}).T
   0  1  2  3  4  5
1  1  4  2  5  3  6
2  7  0  8  1  9  2

您可以使用:

df = pd.DataFrame({'id':[4,5,4],
                   'l1':[7,8,9],
                   'h1':[1,3,5],
                   'l2':[5,3,6],
                   'h2':[4,3,5]}, columns = ['id','l1','h1','l2', 'h2'])
print (df)
   id  l1  h1  l2  h2
0   4   7   1   5   4
1   5   8   3   3   3
2   4   9   5   6   5

df = df.set_index('id')
k = len(df.index)
a = df.values
df = pd.DataFrame(np.vstack((a[:, :2].reshape(1, -1), a[:, 2:].reshape(1, -1))))
#create columns names by range
L = ['l', 'h']
df.columns = ['{}{}'.format(x, y) for y in range(1, k+1) for x in L]
print (df)
   l1  h1  l2  h2  l3  h3
0   7   1   8   3   9   5
1   5   4   3   3   6   5

最新更新