如何使用列名从Series获取值?

时间:2015-12-02 18:11:59

标签: python pandas dataframe

我得到列名列表如下:

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

其中group是Series。我收到了10个列名称列表,例如' Col1_x',' Col2_x'等。

现在我想将Series值读入DataFrame对象:

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

错误消息显示:

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

当我使用group.to_frame()直接将group转换为DataFrame时,结果为0.

完整的代码如下:

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]]

更新: 这是完整的错误消息:

    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"

1 个答案:

答案 0 :(得分:0)

Series.values为您提供创建数据框的值。

如果您尝试将系列转换为一行数据帧,可以这样做,

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
相关问题