0

Excel file:

5432
321
9870

import pandas as pd


file = 'read.xlsx'
df1 = pd.read_excel(file)
print(df1)

I want to sort the number within the number into

2345
1234
0789
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
jjbkd
  • 27
  • 4
  • https://stackoverflow.com/questions/70075110/sort-string-values-delimited-by-commas-in-a-column-using-pandas – coco18 Feb 27 '23 at 08:09

1 Answers1

1

Use list comprehension with convert values to strings with sorted:

#read excel file without header, so column is 0
df1 = pd.read_excel(file, header=None)

df1['new'] = [''.join(sorted(str(x))) for x in df1[0]]
print (df1)
    col
0  2345
1  1234
2  0789
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Hi Jezrael, I got error when copy over – jjbkd Feb 27 '23 at 08:36
  • import pandas as pd file = 'read.xlsx' df = pd.read_excel(file) df['col'] = [''.join(sorted(str(x))) for x in df['col']] print(df) – jjbkd Feb 27 '23 at 08:39
  • import pandas as pd file = 'read.xlsx' df = pd.read_excel(file) print(df.columns) my output is :Int64Index([4321], dtype='int64') – jjbkd Feb 27 '23 at 08:56
  • my excel file is just 5432 3210 9870 – jjbkd Feb 27 '23 at 08:57
  • @jjbkd - Understand, answer is edited. – jezrael Feb 27 '23 at 08:59
  • df['4321'] = [''.join(sorted(str(x))) for x in df['4321']] , indexer = self.columns.get_loc(key) , raise KeyError(key) from err KeyError: '4321' i still get error after changed to 4321 – jjbkd Feb 27 '23 at 09:02
  • @jjbkd - add `header=None` to `read_excel` and then `df[0]` instead `df['4321']` – jezrael Feb 27 '23 at 09:04
  • okok got it many thks i will try to understand your code thks again – jjbkd Feb 27 '23 at 09:05
  • ''.join(sorted(str(x))) "'.join what does this mean"? str(x) is convert to string right? – jjbkd Feb 27 '23 at 09:08
  • @jjbkd - it is called list comprehension - looping by each value of column `df[1]`, convert to string, sorted and join values back to string. – jezrael Feb 27 '23 at 09:09
  • do you have any link for me to read up list comprehension to understand sorry i still new in python still trying to learn thks – jjbkd Feb 27 '23 at 09:17
  • @jjbkd - e.g. check [this](https://www.w3schools.com/python/python_lists_comprehension.asp) – jezrael Feb 27 '23 at 09:30