【问题标题】:apply function and series object应用函数和系列对象
【发布时间】:2019-03-06 15:19:00
【问题描述】:

我想使用apply函数对数据框df的每一行进行排序:

ID   Student1    Student2    Student3  
1    A           B           C
2    M           E           F
3    H           A           D          

代码是

import numpy as np 
import pandas as pd
df = pd.DataFrame(data=np.array([[1, 'A', 'B', 'C'], [2, 'M', 'E', 'F'], [3, 'H', 'A', 'D']]), columns=['ID', 'Student1', 'Student2', 'Student3'])
df1 = df.apply(np.sort, axis = 1) 

df1 是一个数据框,而不是一个系列对象。它看起来像这样:

ID   Student1    Student2    Student3  
1    A           B           C
2    E           F           M
3    A           D           H          

如何获得以下数据框?谢谢。

ID      
1   [A, B, C]     
2   [E, F, M]
3   [A, D, H] 

【问题讨论】:

  • 另外,如果您的问题得到了打击,请选择其中一个作为接受谢谢。

标签: python pandas anaconda


【解决方案1】:

这可以用np.sort 完成没有 使用apply,检查:When should I ever want to use pandas apply() in my code?

import numpy as np 
df.iloc[:,1:]=np.sort(df.iloc[:,1:].values,1)
df
Out[463]: 
   ID Student1 Student2 Student3
0   1        A        B        C
1   2        E        F        M
2   3        A        D        H

然后

s = pd.Series(df.iloc[:,1:].values.tolist(),index=df.ID)
s
Out[466]: 
ID
1    [A, B, C]
2    [E, F, M]
3    [A, D, H]
dtype: object

【讨论】:

    【解决方案2】:

    这就像一个魅力:

    df.set_index(['ID']).agg(list,axis=1).reset_index()
    

    【讨论】:

      猜你喜欢
      • 2018-04-25
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      相关资源
      最近更新 更多