1 回答

TA貢獻1886條經驗 獲得超2個贊
如果稍后需要處理,首先需要將列名轉換為concat字符串:axis=1
df = pd.concat([annual,quarterly], axis=1).rename(columns=str)
print (df)
2015 2016 2017 2018 2019Q1 2019Q2 2019Q3
A 0.417022 0.720324 0.000114 0.302333 0.396767 0.538817 0.419195
B 0.146756 0.092339 0.186260 0.345561 0.685220 0.204452 0.878117
print (df.columns)
Index(['2015', '2016', '2017', '2018', '2019Q1', '2019Q2', '2019Q3'], dtype='object')
print (df['2019Q2'] - df['2018'])
A 0.236484
B -0.141108
dtype: float64
如果想使用句點,有可能,但更復雜:
df = pd.concat([annual,quarterly], axis=1)
print (df)
2015 2016 2017 2018 2019Q1 2019Q2 2019Q3
A 0.417022 0.720324 0.000114 0.302333 0.396767 0.538817 0.419195
B 0.146756 0.092339 0.186260 0.345561 0.685220 0.204452 0.878117
print (df[pd.Period('2018', freq='A-DEC')])
A 0.302333
B 0.345561
Name: 2018, dtype: float64
print (df[pd.Period('2019Q2', freq='Q-DEC')])
A 0.538817
B 0.204452
Name: 2019Q2, dtype: float64
print (df[pd.Period('2019Q2', freq='Q-DEC')] -
df[pd.Period('2018', freq='A-DEC')])
IncompatibleFrequency:輸入與 Period(freq=Q-DEC) 具有不同的 freq=A-DEC
更改名稱Series以防止錯誤:
print (df[pd.Period('2019Q2', freq='Q-DEC')].rename('a') -
df[pd.Period('2018', freq='A-DEC')].rename('a'))
A 0.236484
B -0.141108
Name: a, dtype: float64
在我看來,如果需要處理后Periods最好的值,則以相同的頻率工作:
annual.columns = annual.columns.to_timestamp('Q').to_period('Q')
df = pd.concat([annual,quarterly], axis=1)
print (df)
2015Q1 2016Q1 2017Q1 2018Q1 2019Q1 2019Q2 2019Q3
A 0.417022 0.720324 0.000114 0.302333 0.396767 0.538817 0.419195
B 0.146756 0.092339 0.186260 0.345561 0.685220 0.204452 0.878117
print (df[pd.Period('2019Q2', freq='Q-DEC')] -
df[pd.Period('2018Q1', freq='Q-DEC')])
A 0.236484
B -0.141108
dtype: float64
添加回答
舉報