将Pandas数据框的行转换为列

4
拥有两个类似的panda数据框,如下所示:
Key Value
A    2
A    6
B    7
A    1
B    3
B    4
A    2

如何进行重塑,使其看起来像这样:
A B
2 7
6 3
1 4
2 NaN
2个回答

3
你可以使用groupbyapply创建新的index值:
df = df.groupby('Key').Value.apply(lambda x: pd.Series(x.values)).unstack(0)
print (df)
Key  A  B
0    2  7
1    6  3
2    1  4
3    2  0

使用pivot和通过cumcount创建新的index值是另一种解决方案:

df = pd.pivot(index = df.groupby('Key').cumcount(), columns=df['Key'], values=df['Value'])
print (df)
Key  A  B
0    2  7
1    6  3
2    1  4
3    2  0

df1 = df.groupby('Key').Value.apply(lambda x: pd.Series(x.values)).unstack(0)
print (df1)
Key    A    B
0    2.0  7.0
1    6.0  3.0
2    1.0  4.0
3    2.0  NaN

df2 = pd.pivot(index = df.groupby('Key').cumcount(), columns=df['Key'], values=df['Value'])
print (df2)
Key    A    B
0    2.0  7.0
1    6.0  3.0
2    1.0  4.0
3    2.0  NaN

我正在编辑我的问题,以适应A的数量少于B的情况。 - owise
对我来说,它是有效的,请参见编辑内容。但是如果需要将“int”值与“NaN”一起使用,在pandas中是不可能的。解决方案是将“NaN”替换为诸如“0”的某些值 - print (df1.fillna(0).astype(int)) - jezrael
你可以查看文档 - 整数转换为float64 - jezrael

2

pandas

使用pd.concat、列表推导式和np.unique

s = pd.Series(df.Value.values, df.Key.values)
u = np.unique(s.index.values).tolist()
pd.concat([s.loc[k].reset_index(drop=True) for k in u], axis=1, keys=u)

   A    B
0  2  7.0
1  6  3.0
2  1  4.0
3  2  NaN

numpy

# np.unique can return value counts and an inverse array
# the inverse array will be very helpful in slicing the final
# array we are trying to fill
u, inv, c = np.unique(df.Key.values, return_inverse=True, return_counts=True)

# construct empty array to fill with values
# number of rows equal to the maximum value count
# number of columns equal to the number of unique values
new = np.empty((c.max(), len(u)), dtype=np.float)
new.fill(np.nan)

# construct handy cumulative count per unique value
rows = np.arange(len(inv)) - np.append(0, c[:-1]).repeat(c)

# use slicing arrays to fill empty array
new[rows, inv] = df.Value.values

pd.DataFrame(new, np.arange(c.max()), u)

   A    B
0  2  7.0
1  6  3.0
2  1  4.0
3  2  NaN

时间测试

在此输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接