Mactilda
Mactilda

Reputation: 393

Creating a Pandas data frame using already existing saved variables?

This is probably something basic but I can't seem to find it anywhere. Let's say I have variables created during the process, for example mean absolute error (MAE) calculations (floats). I then have mae_a, mae_b, mae_c, and mae_d. If I'd like to save those to a data frame in pandas, what would I do? It'd be nice if it was something intuitive like:

df = pd.DataFrame(mae_a, mae_b, mae_c, mae_d)

But obviously it isn't that - or I needn't ask.

EDIT: I have understood that I can do like this:

df = pd.DataFrame({'Type':['mae_a', 'mae_b', 'mae_c', 'mae_d'],
                   'MAE':[mae_a, mae_b, mae_c, mae_d]})

To get:
enter image description here

I leave this question unanswered to see if someone has an answer where I don't have to write "mae_a" &c two times - as that would be the ideal.

Upvotes: 0

Views: 1288

Answers (2)

Matthew Barlowe
Matthew Barlowe

Reputation: 2328

If you store your values in a dictionary then you won't have to rewrite the columns when building the dataframe

import pandas as pd
values = {'mae_a': [4.55, 4.66],
          'mae_b': [3.66, 4.66],
          'mae_c': [5.77, 4.66],
          'mae_d': [6.88, 7.55]}


df = pd.DataFrame(values)
df = pd.melt(df, value_vars=df.columns)
print(df)

which gives this output

  variable  value
0    mae_a   4.55
1    mae_a   4.66
2    mae_b   3.66
3    mae_b   4.66
4    mae_c   5.77
5    mae_c   4.66
6    mae_d   6.88
7    mae_d   7.55

Upvotes: 1

moys
moys

Reputation: 8033

You can try this

a = 1,2,3,4,5
b='a','b','c','d','e'
d = pd.DataFrame({'A':a,'B':b})
print(d)

Output

    A   B
0   1   a
1   2   b
2   3   c
3   4   d
4   5   e

Upvotes: 0

Related Questions