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()