0

Given a DataFrame, I'd like to run code that creates a new variable for each column, with the same name as the column.

For example, given this DataFrame:

df = pd.DataFrame({'nums': [1, 2], 'strings': ['a', 'b']})

I want code that produces two Series variables: nums ([1, 2]) and strings (['a', 'b']`).

Max Ghenis
  • 14,783
  • 16
  • 84
  • 132

2 Answers2

1

It is not recommended, but possible also by another solution:

for i in df.columns:
    globals()[i] =  df[i]
print (nums)
0    1
1    2
Name: nums, dtype: int64

So better is create dictionary of Series by DataFrame.to_dict with orient='series' and select by keys:

d = df.to_dict('series')
print(d['nums'])

0    1
1    2
Name: nums, dtype: int64
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0
for i in df.columns:
    exec(i + " = df['" + i + "']")

Running a function may be possible to pass any DataFrame, but I hit scoping issues.

Max Ghenis
  • 14,783
  • 16
  • 84
  • 132