0
$\begingroup$

i GOT this ERROR when doing sampling stratify of a sample dataframe code is like this :

df = pd.DataFrame(dict(
    A=['a', 'a', 'a', 'b', 'c', 'c', 'c', 'a', 'b', 'b', 'b', 'c', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'],
    B=range(20)


 ))


df.sample(n=100, weights='A',replace=True)

it gives me this error:

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

anyone can help?

$\endgroup$
  • $\begingroup$ Weights are supposed to be numeric. What are you wanting the weights to do in this case? $\endgroup$ – Ben Reiniger Aug 7 at 3:13
0
$\begingroup$

Welcome to the site!

I've checked the issue, it's because you are trying to create a sample using a str variable.(df['A']). df.sample cannot create a sample by assigning weights to categorical variable.

I made a small work around i.e.,

df = pd.DataFrame(dict( A=['a', 'a', 'a', 'b', 'c', 'c', 'c', 'a', 'b', 'b', 'b', 'c', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], B=range(20) ))

#converting the text into categorical codes which are in numeric
df['cat'] = df.A.astype('category').cat.codes

#creating a sample using newly created column
Output = df.sample(n=100,weights = 'cat',replace=True)

Output would have 100 records and created using 'cat' for weights.

$\endgroup$
  • $\begingroup$ But these cat codes are more or less arbitrary, right? Why use them as weights? $\endgroup$ – Ben Reiniger Aug 7 at 3:12
  • $\begingroup$ I'm trying to convert each category into a specific number based the cat values weights are assigned. Which is in turn similar to using A. $\endgroup$ – Toros91 Aug 7 at 3:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.