python - 在 Pandas 数据框中按字母顺序排序值

标签 python pandas dataframe

我在 pandas 数据框中有一列称为特征。我想按字母顺序排列“特征”的值。例如下表中,如何获取年龄以下的所有值,按照年龄、颜色、性别的顺序?

ID  Feature
1001    color,age,gender
1002    age,gender,color
1003    age,color,gender
1004    color,age,gender
1005    age,color,gender
1006    color,age,gender
1007    age,color,gender

最佳答案

这是一种方法,但老实说,我不喜欢它:

In [24]: df.Feature = df.Feature.str.split(',', expand=True).apply(lambda x: pd.Series(np.sort(x)).str.cat(sep=','), axis=1)

In [25]: df
Out[25]:
     ID           Feature
0  1001  age,color,gender
1  1002  age,color,gender
2  1003  age,color,gender
3  1004  age,color,gender
4  1005  age,color,gender
5  1006  age,color,gender
6  1007  age,color,gender

关于python - 在 Pandas 数据框中按字母顺序排序值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38373272/

相关文章:

python - 查找重复的字符(分开)

c# - 查看 DLL 文件的内容

python - 怎么设置号 Pandas 数据框最大功能的行数限制

r - 在数据框中的列表中选择具有匹配项的行的快速方法

python - 从 Python 列表中获取字符串?

python - conda的构建字符串的含义是什么?

python - 选择第 n 个中断组索引之前的列

python - 我可以在 pandas 中获得一个额外的标题作为所有列顶部的名称吗

python - 如何在Python中使用group-by函数保留列名?

r - data.frame 到 timeseries 对象