How to sort values in DataFrame for both numerical and string values?
NickName:Fluxy Ask DateTime:2019-12-04T04:35:58

How to sort values in DataFrame for both numerical and string values?

I have the following pandas DataFrame with mixed data types: string and integer values. I want to sort values of this DataFrame in descending order using multiple columns: Price and Name. The string values (i.e. Name) should be sorted in the alphabetical order, or actually can be ignored at all, because the most important ones are numerical values.

The problem is that the list of target columns can contain both string and integer columns, e.g. target_columns = ["Price","Name"]

d = {'1': ['25', 'AAA', 2], '2': ['30', 'BBB', 3], '3': ['5', 'CCC', 2], \
     '4': ['300', 'DDD', 2], '5': ['30', 'DDD', 3],  '6': ['100', 'AAA', 3]}

columns=['Price', 'Name', 'Class']

target_columns = ['Price', 'Name']
order_per_cols = [False] * len(target_columns)

df = pd.DataFrame.from_dict(data=d, orient='index')
df.columns = columns
df.sort_values(list(target_columns), ascending=order_per_cols, inplace=True)

Currently, this code fails with the following message:

TypeError: '<' not supported between instances of 'str' and 'int'

The expected output:

Price    Name    Class
300      DDD     2
100      AAA     3
30       DDD     3
30       BBB     3
25       AAA     2
5        CCC     2

Copyright Notice:Content Author:「Fluxy」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/59164941/how-to-sort-values-in-dataframe-for-both-numerical-and-string-values

Answers
Erfan 2019-12-03T20:48:39

If I understand you correctly, you want a generic way that excludes the object columns from your selection.\n\nWe can use DataFrame.select_dtypes for this, then sort on the numeric columns:\n\n# df['Price'] = pd.to_numeric(df['Price'])\nnumeric = df[target_columns].select_dtypes('number').columns.tolist()\ndf = df.sort_values(numeric, ascending=[False]*len(numeric))\n\n\n Price Name Class\n4 300 DDD 2\n6 100 AAA 3\n2 30 BBB 3\n5 30 DDD 3\n1 25 AAA 2\n3 5 CCC 2\n",


More about “How to sort values in DataFrame for both numerical and string values?” related questions

How to sort values in DataFrame for both numerical and string values?

I have the following pandas DataFrame with mixed data types: string and integer values. I want to sort values of this DataFrame in descending order using multiple columns: Price and Name. The string

Show Detail

How to sort values in DataFrame for both numerical and string values?

I have the following pandas DataFrame with mixed data types: string and integer values. I want to sort values of this DataFrame in descending order using multiple columns: Price and Name. The string

Show Detail

Encoding a feature in Dataframe (both Numerical and Non Numerical)

I want to Encode a feature that contains both Non-Numerical and Numerical Information. This is my code import pandas as pd from sklearn import preprocessing dictionary = {'Values':['Y','N','Y','

Show Detail

Sort pandas dataframe both on values of a column and index?

Is it feasible to sort pandas dataframe by values of a column, but also by index? If you sort a pandas dataframe by values of a column, you can get the resultant dataframe sorted by the column, but

Show Detail

sort xslt with data composed of both text and numerical values

I would like to sort data This is the xml file &lt;item name="HOUSE 10"&gt; &lt;/item&gt; &lt;item name="HOUSE 2"&gt; &lt;/item&gt; &lt;item name="MY 3 APPARTMENT&q

Show Detail

What type of array should I use to combine numerical values and string values and have the ability to sort them in octave/matlab

I'm trying to link numerical (octave/matlab) values in an array to string values in the array how can I go about doing this. The reason I'm trying to do this is to sort the array based on the nume...

Show Detail

Feature Selection in dataset containing both string and numerical values?

Hi I have big dataset which has both strings and numerical values ex. User name (str) , handset(str), number of requests(int), number of downloads(int) ,....... I have around 200 such columns. ...

Show Detail

Groovy sort String format docker tags in numerical order

I have an array of docker image tags values in string format. I was to sort the values in numerical and display in descending order. How can I change the below code to sort in numerical order? cl...

Show Detail

Imputing only the numerical values using sci-kit learn

So, I have a DataFrame that contains a mix of both Categorical and Numerical values that is currently 12345 rows by 171 columns. I have missing values in both the Categorical variable and the Numer...

Show Detail

Sort csv by numerical values

I was looking and reading previous questions and answers similar to mine, but didn't find a good solution to my case. I have a csv file with 2 columns. One is numerical values (100, 40, 350 etc....

Show Detail