Klausos Klausos
Klausos Klausos

Reputation: 16050

How to get values from Series using column names?

I get the list of column names as follows:

featuresA = [str(col) + '_x' for col in group.index]

where group is Series. I receive a list of 10 column names like 'Col1_x', 'Col2_x', etc.

Now I want to read Series values into a DataFrame object:

mergedrow = pd.DataFrame()
mergedrow[featuresA] = group[featuresA]

The error message says:

raise KeyError('%s not in index' % objarr[mask])

When I directly convert group to DataFrame using group.to_frame(), the result is 0.

The complete code looks as follows:

featuresA = [str(col) + '_x' for col in group.index]
featuresB = [str(col) + '_y' for col in match.iloc[[idx]].columns]
mergedrow = pd.DataFrame()
mergedrow[featuresA] = group[featuresA]
mergedrow[featuresB] = match.iloc[[idx]]

UPDATE: This is the whole error message:

    raise KeyError('%s not in index' % objarr[mask])
KeyError: "['airportResources.baggage_x' 'airportResources.arrivalTerminal_x'\n 'arrivalAirportFsCode_x' 'operationalTimes.scheduledGateArrival.dateLocal_x'\n 'schedule.flightType_x' 'schedule.serviceClasses_x' 'status_x'\n 'operationalTimes.actualDateTime_x'] not in index"

Upvotes: 2

Views: 11218

Answers (1)

WoodChopper
WoodChopper

Reputation: 4375

Series.values gives the values for you to create dataframe.

If you are trying to convert series to one row dataframe you could do like this,

import pandas as pd

In [33]: group
Out[33]: 
a    0.316286
b   -0.338733
c   -1.050260
d   -0.365461
e    0.996902
dtype: float64

In [34]: group.index
Out[34]: Index([u'a', u'b', u'c', u'd', u'e'], dtype='object')

In [35]: group.values
Out[35]: array([ 0.31628576, -0.33873327, -1.05026027, -0.3654615 ,  0.99690196])

In [38]: featuresA = [str(col) + '_x' for col in group.index]

In [39]: df = pd.DataFrame([group.values], columns = featuresA)

In [40]: df
Out[40]: 
    a_x       b_x      c_x       d_x       e_x
0  0.316286 -0.338733 -1.05026 -0.365461  0.996902

Upvotes: 2

Related Questions