I have the following column in my Dataframe:
import pandas as pd
x = pd. Series(['R1', 'R2', 70, -100, 0, -25, 'R7', 'R8'])
df = pd.DataFrame(x)
I want to sort the column such that the output is:
['R1', 'R2', 'R7', 'R8', 70, -100, 0, -25]
How can I solve it?
I'm giving this with example to handle the 2 types
which you have mentioned in your question:
import pandas as pd
df = pd.DataFrame()
df['random_vals'] = pd.Series(['R1', 'R2', 70, -100, 0, -25, 'R7', 'R8'])
def sort_by_type(random_types_list):
str_list = []
int_list = []
for elem in random_types_list:
if isinstance(elem, str):
str_list.append(elem)
elif isinstance(elem, int):
int_list.append(elem)
return str_list+int_list
print(sort_by_type(list(df['random_vals'])))
Output of the print
statement:
>>> print(sort_by_type(list(df['random_vals'])))
['R1', 'R2', 'R7', 'R8', 70, -100, 0, -25]
Similarly you can add the code in sort_by_types
method for other data-types
aswell.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.