Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

filter pandas by columns and randomize

Hi i have pandas dataframe

case val1 val2 val3



 1    a   12   13
 1    a   112  413
 2    a   12   113
 2    a   12  113
 2    a   112  13
 3    a   112  163
 3    a   512  513
 3    a   122  135
 3    a   912  513

Now needed to randomly split this for train, test, validation but based on column number case cant be in same folder so in end we have 3 pandas arrays


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

finally i did solved by loop

data = {'case':['case1', 'case1', 'case2', 'case2','case3', 'case3','case3', 'case3','case4', 'case4', 'case4'],
        'Name':['Tom',   'nick', 'krish',  'jack','woo',    'foo',  'bert',  'sia', 'well',  'done',  'today'],
        'Age':[ 20,       21,     19,      18  ,   17,       16,     15,     25 ,    1,       11  , 12]}

df = pd.DataFrame(data)

col = 'case'
sample =[]
variants_data = list(df[col].unique())
print(variants_data)

import random
random_var = variants_data
random.shuffle(random_var)

for casetype in random_var:
    print('--------------')
    dfSel  = df[df[col] == casetype]
    print(dfSel)



- > ====== so results
       > 
       > original table     case    Name    Age 0   case1   Tom 20 1    case1   nick    21
       > 2  case2   krish   19 3    case2   jack    18 4    case3   woo 17 5    case3   foo 16
       > 6  case3   bert    15 7    case3   sia 25 8    case4   well    1 9 case4   done    11
       > 10 case4   today   12
       > 
       > ['case1', 'case2', 'case3', 'case4'] ['case1', 'case4', 'case3',
       > 'case2'] ['case1', 'case4', 'case3', 'case2'] 
       > 
       > out table 
       > --------------
       >     case  Name  Age 0  case1   Tom   20 1  case1  nick   21
       > --------------
       >      case   Name  Age 8   case4   well    1 9   case4   done   11 10  case4  today   12
       > --------------
       >     case  Name  Age 4  case3   woo   17 5  case3   foo   16 6  case3  bert   15 7  case3   sia   25
       > --------------
       >     case   Name  Age 2  case2  krish   19

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...