Select random value from Pandas dataframe, present it to the user, and then delete that value from the dataframe?

Viewed 39

One of my nicer problems in life is that I have a bunch of duplicate Steam keys on hand, whether they're from Humble Bundles or friends or otherwise. I want to build a program that reads a list of keys, spits out a random key from the list, and then deletes it from the list.

So far, I'm able to pull in my keys from a CSV, save it to a dataframe, and pull out a random key

import pandas as pd

df = pd.read_csv('./testCSV.csv')

randomKey = df.sample()
print(randomKey['Key'])

df yields the following dataframe

Product Key
0 Game 1 abcd-efgh-jklm
1 Game 2 da34-2444-1654
2 Game 3 0001-5133-0911
3 Game 4 9fj1-2812-vvvv
4 Game 5 nvow-meow-uhuh
5 Game 6 9302-ca3f-0000
6 Game 7 amjk-un93-cuup
7 Game 8 fork-spon-knif
8 Game 9 091w-iffo-cmww
9 Game 10 p992-1ccc-cppl

Printing randomKey prints a random cell like so:

  Product             Key
5  Game 6  9302-ca3f-0000

...and print(randomKey['Key']) yields the following

5    9302-ca3f-0000
Name: Key, dtype: object

There's a few things I want to do.

  • I want to print just the key from randomKey without the index or product name printed alongside it.
  • I also want to permanently remove the randomKey from df after it is displayed to the user.
  • As a sort of failsafe, I want to add randomKey to a new dataframe to keep track of past keys that have been pulled from df.

I'm also doing all of this in Python with Pandas, so if anyone has recommendations for other libraries or resources that could make this process easier or more efficient, please share.

1 Answers

I think this should do it for you:

# create example dataframe
df = pd.read_html("https://stackoverflow.com/questions/73733987/select-random-value-from-pandas-dataframe-present-it-to-the-user-and-then-dele")[0]

# create new dataframe
new_df = pd.DataFrame()

while not df.empty:
    key = df.sample()                    # sample random key
    new_df = pd.concat([new_df, key])    # add key to new df
    df = df.drop(index=key.index)        # remove key from old df 
    print(key.Key.values[0])             # print only key

Output:
enter image description here

Related