在Pandas中使用Python将列数据处理为新格式

时间:2016-05-18 21:38:23

标签: python pandas

我正在尝试使用pandas来操纵我的数据。我的数据看起来像这样:

CarModel ProductionData ProductionYear
BMWX1    55000          2005
Accord   100000         2005
BMWX1    34000          2006
Accord   110000         2006
BMWX1    43000          2007
Accord   105000         2007

如何使数据看起来像这样?

CarModel NewColumn
BMWX1    [2005.0, 2006.0, 55000]; [2006.0, 2007.0, 34000]; [2007.0, 2008.0,      43000]
Accord   [2005.0, 2006.0, 100000]; [2006.0, 2007.0, 110000]; [2007.0, 2008.0,      105000]

2 个答案:

答案 0 :(得分:0)

以下产生您描述的输出。在CarModel上进行分组(column或移至index),然后将相应的列返回为.values

df['Year2'] = df.ProductionYear.add(1)
df.groupby('CarModel').apply(lambda x: x.loc[:, ['ProductionYear', 'Year2', 'ProductionData']].values)

CarModel
Accord    [[2005, 2006, 100000], [2006, 2007, 110000], [...
BMWX1     [[2005, 2006, 55000], [2006, 2007, 34000], [20...
dtype: object

答案 1 :(得分:0)

设置

text = """CarModel ProductionData ProductionYear
BMWX1    55000          2005
Accord   100000         2005
BMWX1    34000          2006
Accord   110000         2006
BMWX1    43000          2007
Accord   105000         2007"""

df = pd.read_csv(StringIO(text), delim_whitespace=1)

解决方案

gb = df.set_index('CarModel').groupby(level=0)

def proc_df(df):
    # Add this column becuase OP has it in final output
    df['Year2'] = df.ProductionYear + 1

    columns = ['ProductionYear', 'Year2', 'ProductionData']

    # Return ndarray gets flattened to string when returned via apply
    return df[columns].values

gb.apply(proc_df)

看起来像:

CarModel
Accord    [[2005, 2006, 100000], [2006, 2007, 110000], [...
BMWX1     [[2005, 2006, 55000], [2006, 2007, 34000], [20...
dtype: object