猿问

尝试将数据框中的行更改为列

我试图返回一个数据框,其中我的行和我的列,反之亦然。


这是我的代码:


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)



这是我正在使用的数据框: 

泛舟湖上清波郎朗
浏览 156回答 3
3回答

jeck猫

创建工作区import randomimport pandas as pd# your variablesmy_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 valuesser = []for x in range(0,len(cols)):&nbsp; &nbsp; a = [random.uniform(0,1) for _ in range(len(my_names))]&nbsp; &nbsp; ser.append(a)# also swapped the pd.concat to create a dataframe as your image-example showsdf = pd.DataFrame(ser, columns=my_names, index = cols)解决方案:# a simple transpose will do the trick for what you need:df.T

潇湘沐

这个操作其实是pandas直接提供的。只需使用transpose()orT函数(参考)。您必须添加的唯一行是:df_transposed&nbsp;=&nbsp;df.T

慕盖茨4494581

怎么样:df.transpose()我认为应该这样做。试一试。顺便说一句,您生成数据帧的代码有很多错误,或者我使用它的方式错误。
随时随地看视频慕课网APP

相关分类

Python
我要回答