简体   繁体   English

Pandas 数据帧转置

[英]Pandas Dataframe Transpose

I have tried to find something that could help me but I couldn't.我试图找到可以帮助我的东西,但我不能。 I'd appreciate if someone could link me to it, if my question is already answered.如果我的问题已经得到解答,如果有人可以将我链接到它,我将不胜感激。

I have a pandas dataframe that has row-wise features.我有一个具有行功能的熊猫数据框。 For example:例如:

   Patient_ID  Feature_Id  Feature_Value
0           3          10           0.30
1           3          50           0.20
2           3          60           1.00
3           4          10           0.25

I need to convert them into column-wise features(essentially columns in Pandas) -- something like below:我需要将它们转换为逐列特征(本质上是 Pandas 中的列)——如下所示:

Patient_Id    10   50   60
         3  0.30  0.2  1.0
         4  0.25  Nan  Nan

You could try pd.pivot_table你可以试试pd.pivot_table

In [16]: pd.pivot_table(df, index='Patient_ID', values='Feature_Value', columns='Feature_ID')
Out[16]: 
Feature_ID    10   50   60
Patient_ID                
3           0.30  0.2  1.0
4           0.25  NaN  NaN

Note that if you need to specify what to do if more than a single entry exists (which you don't have in your example), you can use the aggfunc parameter (the default is to calculate the mean).请注意,如果您需要指定在存在多个条目时要执行的操作(在您的示例中没有),您可以使用aggfunc参数(默认值是计算平均值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM