我想更新 pandas 数据框中的列以按字母顺序重新排列字符串。 例如,如果有一个名为“Number”的列,其中包含:[123、321、456、654],我希望它按字母顺序对每个字符串条目进行排序,并将其添加为新列。
# List of Number
numbers = [123, 321, 456, 654]
# Create a DataFrame object
df = pd.DataFrame(numbers, columns =['Number'])
输出应该是:
我是 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/