Python 如何使用列名从序列中获取值?
我得到的列名列表如下:Python 如何使用列名从序列中获取值?,python,pandas,dataframe,Python,Pandas,Dataframe,我得到的列名列表如下: featuresA = [str(col) + '_x' for col in group.index] 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[features
featuresA = [str(col) + '_x' for col in group.index]
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]]
其中,组是系列。我收到了一个包含10个列名的列表,如“Col1\u x”、“Col2\u x”等
现在,我想将系列值读入DataFrame对象:
mergedrow = pd.DataFrame()
mergedrow[featuresA] = group[featuresA]
错误消息显示:
raise KeyError('%s not in index' % objarr[mask])
当我使用group.to_frame()将group
直接转换为数据帧时,结果是0
完整的代码如下所示:
featuresA = [str(col) + '_x' for col in group.index]
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"
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
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
你能帮我发两行吗
mergedrow[featuresA]=group[featuresA]
实际上您的数据帧尚未创建,因此,当您使用mergedrow[featuresA]
时,出现关键错误。您可以发布两行组吗mergedrow[featuresA]=组[featuresA]
实际上您的数据帧尚未创建,因此,当您使用mergedrow[featuresA]
时,会引发关键错误。