0

Is there a way to convert pandas dataframe to vectors? For example,

df
Out[53]: 
     Col1
3    Place
4    Country

Expected output

df_converted = 'Place','Country'
smci
  • 32,567
  • 20
  • 113
  • 146
vit p
  • 21
  • 1
  • 6
  • Expected output: `df_converted = 'Place','Country'` does't make sense in either Python or pandas. Do you mean a list `['Place','Country'`]`, a pandas array, a numpy array, numpy vector...? And what do you ultimately want to do with the list/vector, use it in a computation? – smci Feb 01 '21 at 07:58
  • Also please tag and title pandas stuff [tag:pandas] not just [tag:python], that will help it get seen and get you get faster answers from pandas users. – smci Feb 01 '21 at 08:00

2 Answers2

1

Pandas dataframes are consisted of Series, the code that you shared above is about converting a Serie into a list. You can simply run following code ;

df_converted = list(df["Col1"])

If you want to convert a dataframe into another format such as a numpy array you can find more info at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html for the to_numpy() method.

1

You can use method values on a series. This returns a numpy array.

import pandas as pd

df = pd.DataFrame({
    'Col1': ['Place', 'Country'],
    'Col2': ['This', 'That'],
})

vector = df['Col1'].values

print(vector)
print(type(vector))

Output

['Place' 'Country']
<class 'numpy.ndarray'>
Maxim Ivanov
  • 299
  • 1
  • 6