Appropriate Time to Dynamically Set Variable Names?
<p>Edit: Turns out the answer is an emphatic "no". However, I'm still struggling to populate the lists with the right amount of entries. </p>

<hr>

<p>I've been searching StackOverflow all over for this, and I keep seeing that dynamically setting variable names is not a good solution. However, I can't think of another way to to this. </p>

<p>I have a <code>DataFrame</code> created from <code>pandas</code> (read in from excel) that has columns with string headers and integer entries, and one column that has the numbers (let's call it Week) 1 through 52 increasing sequentially. What I want to do is create separate lists each named for the column headers and the entry is the week number appearing the number of times of the listed integer. </p>

<p>This is simple for a few columns, just manually create lists names, but as the number of columns grows, this could get a little out of hand.</p>

<p>Atrocious explanation, it was the best I could come up with. Hopefully a simplified example will clarify. </p>

<pre><code>week  str1    str2    str3   
1       8       2        5        
2       1       0        3    
3       2       1        1 
</code></pre>

<p>Desired output:</p>

<pre><code>str1_count = [1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3] # eight 1's, one 2, and two 3's
str2_count = [1, 1, 3]                         # two 1's, one 3
str3_count = [1, 1, 1, 1, 1, 2, 2, 2, 3]       # five 1's, three 2's, one 3
</code></pre>

<p>What I have so far: </p>

<pre><code>results = {}
df = pd.DataFrame(from_csv(...., sep = ","))
for key in df:
    for i in df[key]
        results[key] = i # this only creates a list with the int value of the most recent i
</code></pre>

<p>So, like this?</p>

<pre><code>import collections
import csv
import io

reader = csv.DictReader(io.StringIO('''
week,str1,str2,str3
1,8,2,5
2,1,0,3
3,2,1,1
'''.strip()))

data = collections.defaultdict(list)
for row in reader:
    for key in ('str1', 'str2', 'str3'):
        data[key].extend([row['week']]*int(row[key]))

from pprint import pprint
pprint(dict(data))

# Output:
{'str1': ['1', '1', '1', '1', '1', '1', '1', '1', '2', '3', '3'],
 'str2': ['1', '1', '3'],
 'str3': ['1', '1', '1', '1', '1', '2', '2', '2', '3']}
</code></pre>

<p>Note: Pandas is good for crunching data and doing some interesting operations on it, but if you just need something simple you don't need it. This is one of those cases.</p>

python pandas dataframe