[英]Converting Pandas dataframe rows to columns
I have the following pandas dataframe with 4000 rows我有以下 4000 行的熊猫数据框
A B C
xq 34 1
xy 23 1
xt 13 1
xq 55 2
xy 66 2
xt 77 2
xq 12 3
xt 89 3
xq 90 4
xy 45 4
xt 12 4
What would be an efficient method to convert it to a pandas dataframe as shown below?将其转换为熊猫数据框的有效方法是什么,如下所示?
id xq xy xt
1 34 23 13
2 55 66 77
3 12 89
4 90 45 12
You already have the answer from @sammywemmy.你已经从@sammywemmy 那里得到了答案。
If you want to remove the multi_level, you can reset index and rename column C to id.如果要删除multi_level,可以重置索引并将列C 重命名为id。
import pandas as pd
x = [['xq', 34, 1],
['xy', 23, 1],
['xt', 13, 1],
['xq', 55, 2],
['xy', 66, 2],
['xt', 77, 2],
['xq', 12, 3],
['xt', 89, 3],
['xq', 90, 4],
['xy', 45, 4],
['xt', 12, 4]]
df = pd.DataFrame(x, columns = ['A','B','C'])
df1 = (df.pivot(index='C', columns='A', values='B')
.fillna('')
.reset_index()
.rename(columns = {'C':'id'}))
print (df1)
The output will be:输出将是:
A id xq xt xy
0 1 34.0 13.0 23.0
1 2 55.0 77.0 66.0
2 3 12.0 89.0
3 4 90.0 12.0 45.0
Note that you didn't have a xy value for 3, so it is a NaN.请注意,您没有 3 的 xy 值,因此它是 NaN。 By adding .fillna(''), the NaN value is set to empty string.
通过添加 .fillna(''),将 NaN 值设置为空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.