如何摆放 pandas 数据帧中每行的行值? [英] How can i pivot down my row values for each row in pandas dataframe?

查看:206
本文介绍了如何摆放 pandas 数据帧中每行的行值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框架:

    Name  Percent Subject1 Subject2
  ramesh       85    Maths  Science
     ram       42    Maths      
     Raj       85      NaN  Science

输出数据框:

     Name  Percent  Subject
   ramesh       85    Maths
   ramesh       85  Science
      ram       42    Maths
      Raj       85  Science


推荐答案

pd.lreshape 可以将多列的值组合成一个:

pd.lreshape can combine the values from multiple columns into one:

import numpy as np
import pandas as pd
nan = np.nan
df = pd.DataFrame({'Name': ['ramesh', 'ram', 'Raj'],
                   'Percent': [85, 42, 85],
                   'Subject1': ['Maths', 'Maths', nan],
                   'Subject2': ['Science', nan, 'Science']})

print(pd.lreshape(df, {'Subject':['Subject1', 'Subject2']}))

b
$ b

yields

     Name  Percent  Subject
0  ramesh       85    Maths
1     ram       42    Maths
2  ramesh       85  Science
3     Raj       85  Science






pd.lreshape 中似乎没有记录(但是?)在线文档。这是它的docstring:


pd.lreshape does not appear to be documented (yet?) in the online docs. Here is its docstring:

In [40]: help(pd.lreshape)
Help on function lreshape in module pandas.core.reshape:

lreshape(data, groups, dropna=True, label=None)
    Reshape long-format data to wide. Generalized inverse of DataFrame.pivot

    Parameters
    ----------
    data : DataFrame
    groups : dict
        {new_name : list_of_columns}
    dropna : boolean, default True

    Examples
    --------
    >>> import pandas as pd
    >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526],
    ...                      'team': ['Red Sox', 'Yankees'],
    ...                      'year1': [2007, 2008], 'year2': [2008, 2008]})
    >>> data
       hr1  hr2     team  year1  year2
    0  514  545  Red Sox   2007   2008
    1  573  526  Yankees   2007   2008

    >>> pd.lreshape(data, {'year': ['year1', 'year2'], 'hr': ['hr1', 'hr2']})
          team   hr  year
    0  Red Sox  514  2007
    1  Yankees  573  2007
    2  Red Sox  545  2008
    3  Yankees  526  2008

    Returns
    -------
    reshaped : DataFrame

这篇关于如何摆放 pandas 数据帧中每行的行值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆