If there's a variable in an output is there a way to bring it into use?

Viewed 43

Out of this Pandas table, I did some work.


   england     best       six      euros
0   kane      grealish  sancho     sterling
1   foden     mount     bellingham reece
2   trippier stones     walker     coady

Here's my code:

for i in range(0, 3):
    for g in range(1, 4):
        if i+1==g:
            a = f'''r{g} = {list(df.iloc[i])}'''
            print(a)

My Output:

r1 = ['kane', 'grealish', 'sancho', 'sterling']
r2 = ['foden', 'mount', 'bellingham', 'reece']
r3 = ['trippier', 'stones', 'walker', 'coady']

I've got three variables as an output, but is there a way to get them into local use? Like, print(r1) should give me ['kane', 'grealish', 'sancho', 'sterling']

Is there a way? Thanks in advance.

2 Answers

You can use dictionary, with keys "r1", "r2", etc. For example:

d = {"r{}".format(i): v for i, v in enumerate(df.apply(list, 1), 1)}
print(d)

Prints:

{'r1': ['kane', 'grealish', 'sancho', 'sterling'], 
 'r2': ['foden', 'mount', 'bellingham', 'reece'], 
 'r3': ['trippier', 'stones', 'walker', 'coady']}

print(d["r1"])

Prints:

['kane', 'grealish', 'sancho', 'sterling']

Also, to print row 0 as a list you can use directly .loc:

print(df.loc[0, :].tolist())

Prints:

['kane', 'grealish', 'sancho', 'sterling']

You can create a dictionary like @Andrej has suggested or convert your data frame to a list, then access each row by index. It's not a good practice to create dynamic variables r1, r2, r3 in global namespace since it will pollute your namespace and also make those variables difficult to manage:

lst = df.values.tolist()
lst[0]
# ['kane', 'grealish', 'sancho', 'sterling']

lst[1]
# ['foden', 'mount', 'bellingham', 'reece']

lst[2]
# ['trippier', 'stones', 'walker', 'coady']
Related