0

I have a pandas data.frame

temp = pd.DataFrame({'country':['C1','C1','C1','C1','C2','C2','C2','C2'],
                     'seg':    ['S1','S2','S1','S2','S1','S2','S1','S2'],
                     'agegroup':    ['1', '2', '2', '1','1', '2', '2', '1'],
                      'N' : [21,22,23,24,31,32,33,34]})

and a vector like

vector = ['country', 'seg']

what i want to do is to create two vectors with names vector_country and vector_seg which will contain the respective columns of the temp, in this case the columns country and seg

I have tried

for vec in vector:
    'vector_' + str(vec) = temp[[vec]]

So in the end I would like to end up with two vectors:

vector_country, which will contain the temp.country and

vector_seg, which will contain the temp.seg

Is it possible to do something like that in python ?

jpp
  • 159,742
  • 34
  • 281
  • 339
quant
  • 4,062
  • 5
  • 29
  • 70
  • Is [this](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.as_matrix.html) what you want? Or [this](https://stackoverflow.com/a/37043071/2454357)? – Thomas Kühn Feb 02 '18 at 10:04
  • What's wrong with using ```vector_country=temp['country'].values; vector_seg=temp['seg'].values```? – TrigonaMinima Feb 02 '18 at 10:10
  • @ThomasKühn neither. the problem is that i want to create two vectors with different names depending on the value of `vector`. I edited my question. I hope it is more clear now – quant Feb 02 '18 at 10:12
  • @TrigonaMinima because i want to do it in a standardized way for multiple columns – quant Feb 02 '18 at 10:12

1 Answers1

2

Do not try and dynamically name variables. This is bad practice, will make your code intractable.

A better alternative is to use dictionaries, as so:

v = {}

for vec in ['country', 'seg']:
    v[vec] = temp[vec].values
jpp
  • 159,742
  • 34
  • 281
  • 339
  • I agree that this is the way to go, but why would one want to switch from a DataFrame to storing arrays in a dict? – Thomas Kühn Feb 02 '18 at 10:14
  • 1
    @ThomasKühn, if the dataframe is going to be discarded and you want to efficiently store the values for some later calculations. I don't know the complete workflow for quant's use case. – jpp Feb 02 '18 at 10:15