我试图返回一个数据框,其中我的行和我的列,反之亦然。这是我的代码:my_names = [2009,2010,2011,2012,2013,2014,2015,2016,2017,2018]cols = ['link', 'post','shared','timeline','status']ser = [nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen]df = pd.concat(ser, axis=1, keys=my_names)我试图让我们 pd.pivot 做到这一点:df1 = df.pivot(index=df.columns, columns=df.index, values=df.values)但这是我收到的回溯:---------------------------------------------------------------------------KeyError Traceback (most recent call last)<ipython-input-23-c08b1071deea> in <module>()----> 1 df1 = df.pivot(index=df.columns, columns=df.index, values=df.values)/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in pivot(self, index, columns, values) 4380 """ 4381 from pandas.core.reshape.reshape import pivot-> 4382 return pivot(self, index=index, columns=columns, values=values) 4383 4384 _shared_docs['pivot_table'] = """/usr/local/lib/python3.6/dist-packages/pandas/core/reshape/reshape.py in pivot(self, index, columns, values) 385 else: 386 index = self[index]--> 387 indexed = Series(self[values].values, 388 index=MultiIndex.from_arrays([index, self[columns]])) 389 return indexed.unstack(columns)/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in __getitem__(self, key) 2131 if isinstance(key, (Series, np.ndarray, Index, list)): 2132 # either boolean or fancy integer index-> 2133 return self._getitem_array(key) 2134 elif isinstance(key, DataFrame): 2135 return self._getitem_frame(key)这是我正在使用的数据框:
3 回答
jeck猫
TA贡献1909条经验 获得超7个赞
创建工作区
import random
import pandas as pd
# your variables
my_names = [2009,2010,2011,2012,2013,2014,2015,2016,2017,2018]
cols = ['link', 'post','shared','timeline','status']
# since we don't have the list of variables in ser, I'm creating it and creating a list of lists of values
ser = []
for x in range(0,len(cols)):
a = [random.uniform(0,1) for _ in range(len(my_names))]
ser.append(a)
# also swapped the pd.concat to create a dataframe as your image-example shows
df = pd.DataFrame(ser, columns=my_names, index = cols)
解决方案:
# a simple transpose will do the trick for what you need:
df.T
添加回答
举报
0/150
提交
取消