簡體   English   中英

在Pandas DataFrame中合並行

[英]Combine Rows in Pandas DataFrame

我有針對不同公司的財務績效指標,每年一列。 現在,我希望連續列出特定年份的每個公司的所有指標。

現在我的數據看起來像這樣:

import numpy as np
import pandas as pd


startyear = 2014
endyear = 2015

df = pd.DataFrame(np.array([
['AAPL',  2014,  0.2,  0.4,  1.5],
['AAPL',  2015,  0.3,  0.4,  2.0],
['AAPL',  2016,  0.2,  0.3,  1.5],
['GOGL',  2014,  0.4,  0.5,  0.5],
['GOGL',  2015,  0.6,  0.8,  1.0],
['GOGL',  2016,  0.3,  0.5,  2.0]]), 
columns=['Name',  'Year',  'ROE',  'ROA',  'DE'])

newcolumns = (df.columns + [str(startyear)]).append(df.columns + [str(endyear)])

dfnew=pd.DataFrame(columns=newcolumns)

我想擁有的是(例如僅2014和2015年):

Name  ROE2014 ROA2014 DE2014 ROE2015 ROA2015 DE2015
AAPL  0.2     0.4     1.5    0.3     0.4     2.0
GOOGL 0.4     0.5     0.5    0.6     0.8     1.0

到目前為止,我只設法獲得了新的列名,但是不知何故我無法理解如何填充這個新的DataFrame。

創建新的DataFrame,然后調整列名稱可能更容易:

# limit to data you want
dfnew = df[df.Year.isin(['2014', '2015'])]

# set index to 'Name' and pivot 'Year's into the columns 
dfnew = dfnew.set_index(['Name', 'Year']).unstack()

# sort the columns by year
dfnew = dfnew.sortlevel(1, axis=1)

# rename columns
dfnew.columns = ["".join(a) for a in dfnew.columns.values]

# put 'Name' back into columns
dfnew.reset_index()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM