pythonpandasrowstablesorterpython-3.9

order only number in dataframe rows by rows import from csv


I want to get ascending order all number of dataframe imported from a CSV file row-by-row:

I tried:

df_tirage = pd.read_csv('lotodata.csv', sep = ',', usecols=['day','month_year','num0','num1','num2','num3','num4','chance'])
for eachline in df_tirage:
    line = map(str, eachline.split(","))
    sorted_line = sorted(line)

df-tirage


Solution

  • If I'm understanding it correctly, something might the following should do the trick.

    df_tirage = pd.read_csv('lotodata.csv', sep = ',', usecols=['day','month_year','num0','num1','num2','num3','num4','chance'])
    
    def sorter(num_arr):
        return np.sort(num_arr)
    
    df_tirage[['num0', 'num1', 'num2', 'num3', 'num4']] = df_tirage.apply(lambda row : sorter(row[2:-1]), axis=1, result_type='expand')
    

    We're essentially applying a sorting function row by row using lambda and then unpacking the sorted values into dataframe columns as we go.