Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 应用函数和序列对象_Python_Pandas_Anaconda - Fatal编程技术网

Python 应用函数和序列对象

Python 应用函数和序列对象,python,pandas,anaconda,Python,Pandas,Anaconda,我想使用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

我想使用
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] 

这可以通过
np完成。使用
apply
,在不使用
的情况下进行排序,检查:

然后


这就像一个符咒:

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

此外,如果您的问题得到了回答,请选择其中一个作为“接受感谢”。
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
df.set_index(['ID']).agg(list,axis=1).reset_index()