Convert pandas data frame to array

Asked

Viewed 6,769 times

0

I have a data that, from . txt, I converted to a Dataframe (DF) with pandas. For the various activities I performed it is very convenient to be a DF.

There is only one column with values, beyond the index.

DF

Now, I would like to convert DF into an array.

How can I do that?

  • 1

    Something like lista = df['nome_coluna'].tolist()?

  • 1

    Klel, see if that helping

  • Alexciuffa, I got the error: 'Dataframe' Object has no attribute 'tolist'

  • Tuxpilgrim, is that my data is just a column, it would need that when converting to the array, it becomes only a row.

2 answers

3

Klel, in this case Voce can use the function:

'pandas.DataFrame.values'

Follow the example of use:

import pandas as pd
df = pd.DataFrame({'idade':    [ 3,  29],
                   'peso': [94, 170]})
vetor = df.values

To pass all DF to an array.

Or directly assign a single column to an array.

import pandas as pd
df = pd.DataFrame({'idade':    [ 3,  29],
                   'peso': [94, 170]})
vetor = df['idade'].values

In the last row just place desired column.

Follows the Link for documentation.

Example with 1 column

import pandas as pd
df = pd.DataFrame({'idade':[ 3,29,13,15,16,14,12]})
vetor = df.values
  • Hello Clayton, the problem is that my data is just a column, it would need that when converting to the array, it becomes only a row.

  • The issue of being a single column has no Klel problem. I added an example containing only one column

0

Another method you can use is the to_numpy()

This method converts a Dataframe into a Numpy array.

df.to_numpy()

array([[nan, 0.2, nan],
       [nan, nan, 0.5],
       [nan, 0.2, 0.5],
       [0.1, 0.2, nan],
       [0.1, 0.2, 0.5],
       [0.1, nan, 0.5],
       [0.1, nan, nan]])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.