0

I have a list of 1000 records in it. The list is a mixture of int values and str values for example

    df.head()
+-------+
|   0   |
+-------+
| asber |
| cdedg |
| hfowe |
| idcpo |
| fukvm |
| 123   |
| 456   |
| 789   |
| 012   |
+-------+

I want all the numerical value in one side and all categorical value in another side basically, make 2 new list one with all numerical value and another with categorical value

Please let me know if there is a solution for this..

Pynchia
  • 9,316
  • 4
  • 29
  • 41
Charan
  • 51
  • 2

3 Answers3

2

As you described in the comment your number values are also in the string format.

valuelist = ['abc', 'xyz', '123', '456']
numberlist = list()
strlist = list()
for num in valuelist:
    if num.isdigit():
        numberlist.append(int(num)) #do type cast for conversion
    else:
        strlist.append(num)

now you can print or iterate both the lists based on your uses.

Harshil jain
  • 318
  • 1
  • 8
0

For a list,

lis = [1, 2, 3, 'ab', 'bc', 'ac']
import numbers
lis1 = []
lis2 = []
for i in lis:
    if isinstance(i, numbers.Integral):
        lis1.append(i)
    else:
        lis2.append(i)

This will output

lis1 = [1, 2, 3]
lis2 = ['ab', 'bc', 'ac']
Swati Srivastava
  • 831
  • 1
  • 8
  • 11
  • I have an issue all my numeric values are also marked as str, in this case, what can I do? For ex: it's not 123 but its '123' – Charan Jan 27 '20 at 12:38
  • You can do the following import numbers lis1 = [] lis2 = [] for i in lis: try: if isinstance(int(i), numbers.Integral): lis1.append(i) except: lis2.append(i) It tries to convert the string to int, but if it cannot be converted, as for the case of 'ab', it goes to except block. Otherwise, it checks for the integer equivalent. Hope it helps! – Swati Srivastava Jan 28 '20 at 06:02
0

You can do

categorical = [i for i in df["0"] if not i.isdigit()]
numerical = [int(i) for i in df["0"] if i.isdigit()]

Note: Although this looks compact, it is using 2 for loops, you can do it with single for loop like @HarshilJain's answer

Sociopath
  • 11,667
  • 16
  • 38
  • 61