2016-07-17 37 views
-1
import pandas as pd 

df = pd.DataFrame({Company : ['abc','def','ghi']} {"2010" : [0,100,230]} {"2011" : [120,0,300]} {"2012" : [130,240,0]}) 

選擇從那裏一年預訂大於0

for column_name, column in df.transpose().iterrows(): 
    first_column = df[column_name > 0].index[0] 
    first_column_value = df.iloc[first_column] 

從FIRST_COLUMN選擇第三列列的第一個單元格

second_column_value = df.iloc[first_GPS_index+2] 

計算CAGR

df['CAGR'] = (first_column.div(second_column).pow(1./2)- 1)).sub(1))*100 

請幫助我,我收到錯誤。我是新來的Python 結果公司First_Column_Value Second_Column_Value ABC 100 230 高清120 300如何選擇每行一列的位置,如果條件匹配

+3

你能修復數據幀構造函數的代碼嗎?這不是一個有效的字典。 – ayhan

+0

嗨阿伊漢,我很抱歉,我沒有得到你的問題。我很抱歉,我對Python非常陌生,或者你可以說編程 –

+1

@PrankitRa你需要修正你的代碼中的語法。現在,它不會運行 – sirfz

回答

0

我固定下大約爲字典和公司作爲一個列表中提供的一些數據假設你的代碼。隨意交換年份和公司名稱。如果這樣做,則不需要使用DataFrame的轉置。

查看在代碼註釋用於進一步的解釋:

import pandas as pd 

# sample data 
company_names = ['Company A','Company B','Company C'] 
data = {"2010" : [0,100,230], "2011" : [120,0,300], "2012" : [130,240,0]} 

# create DataFrame 
df = pd.DataFrame(data, index=col_names) 

# since the data is not provided in the correct way (rows and columns are swapped) 
# we need to get the transpose of the DataFrame before further processing 
df = df.T 

# sort index in order to make sure that years are sorted chronologically 
df.sort_index(inplace=True) 
print(df) 

# iterate through all columns and get the first index element where condition applies 
# and store in dict 
out = {} 
for col in df: 
    out[col] = df[df[col] > 0].index.tolist()[0] 
print(out) 

給予作爲輸出:

 Company A Company B Company C 
2010   0  100  230 
2011  120   0  300 
2012  130  240   0 
{'Company B': '2010', 'Company A': '2011', 'Company C': '2010'} 

因此,例如,B公司有其第一登記服務在2010年

爲了計算CAGR動態類型您需要知道您可以假設爲您的時間間隔,並確保每年都有數據。另一種方法是使用時間戳索引並使用timedeltas計算時間間隔。

爲了簡單起見,我認爲你可以確保有每年和硬編碼一年的時間間隔完整數據:

# assume to have a time interval of one year 
delta_t = 1 

# in order to divide to rows we apply `df.div()` which basically divides two DataFrames. 
# To divide each row with the following row we apply `df.shift(1)` to the same DataFrame 
# in order to shift the DataFrame by one row (see docs on used commands for futher details). 
cagr = ((df.div(df.shift(1)))**(1/delta_t) -1)*100 
print(cagr) 

,並提供:

 Company A Company B Company C 
2010  NaN   NaN   NaN 
2011  inf -100.000000 30.434783 
2012 8.333333   inf -100.000000 

過濾這個數據是爲了得到適用的結果是由你自己決定的,因爲從經濟角度來看,NaN(或者甚至是inf)的CAGR沒有多大意義。

+0

謝謝艾伯特!它的幫助很大! –

+0

這是否解決了您的問題?如果是這樣,請接受我的回答以便將您的問題標記爲已解決。 – albert

+0

嗨艾伯特,我很新來堆棧溢出。你能幫我解決如何接受你的答案? –

相關問題