python - 按字母顺序对单元格文本排序

标签 python pandas dataframe

我想更新 pandas 数据框中的列以按字母顺序重新排列字符串。 例如,如果有一个名为“Number”的列,其中包含:[123、321、456、654],我希望它按字母顺序对每个字符串条目进行排序,并将其添加为新列。

# List of Number 
numbers = [123, 321, 456, 654]
# Create a DataFrame object 
df = pd.DataFrame(numbers, columns =['Number'])

输出应该是:

enter image description here

我是 pandas 和 python 的新手,所以非常感谢逐步分解和解释代码

最佳答案

您可以使用apply 和自定义函数:

df['Number2'] = df['Number'].apply(lambda x: ''.join(sorted([num for num in str(x)])))

print(df)

   Number Number2
0     123     123
1     321     123
2     456     456
3     654     456

分割:

# Step 1: break the cells into a list of values
>>> df['Number'].apply(lambda x: [num for num in str(x)])

0    [1, 2, 3]
1    [3, 2, 1]
2    [4, 5, 6]
3    [6, 5, 4]

# Step 2: sort the values within a list
>>> df['Number'].apply(lambda x: sorted([num for num in str(x)]))

0    [1, 2, 3]
1    [1, 2, 3]
2    [4, 5, 6]
3    [4, 5, 6]

# Step 3: join the sorted values and convert to int (if necessary)
>>> df['Number'].apply(lambda x: ''.join(sorted([num for num in str(x)]))).astype(int)

0    123
1    123
2    456
3    456
Name: Number, dtype: int32

关于python - 按字母顺序对单元格文本排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72701047/

相关文章:

r - "number of items to replace is not a multiple of replacement length"从半长整形到长整形时

python - 将数据框中字符串列的唯一值转换为值为 0 或 1 的新多 header

python - 使用 pandas 将数据框导出到 python 中的 csv 文件

python - 动态构建 bool 表达式

python - beautifulsoup 获取站点的所有 url

python - 删除*几乎*重复的观察 - Python

python - Pandas:用具有相同固定重复次数的数据帧填充固定数量的新列

Python Pandas 在 read_csv 中结合时间戳列和 fillna

python - 构建 MySQL Python 模块时出错

python - 将当前的product_id传递给Django中的模型