2016-11-30 36 views
1

使用Python 3編碼和 大熊貓版本0.18.1如何使用熊貓dataframes從用戶輸入

我試圖讓通過給用戶選擇,從數據幀過濾數據我的程序更有活力。

我的問題是:

1)如何讓我的用戶選擇,可用於在數據幀的過濾?

2)有沒有更好的方法來做到這一點?與功能或類Mabye?

假設我的DF如下:

df.dtypes 

PIID object  
fy  object 
zone object 

如果FY進行分組:

df.groupby('fy').PIID.count() 

fy 
2014 38542 
2015 33629 
2016 32789 

如果區域劃分:

df.groupby('zone').PIID.count() 

AZW - Acquisition Zone West  3909 
NAZ - Northern Acquisition Zone 1167 
SAZ - Southern Acquisition Zone 2983 

通常我可以只創建一個新的數據幀通過執行以下過濾器:

year = df['fy'] == '2016'  
zone = df['zone'] == 'AZW - Acquisition Zone West' 

newdf = df[year & zone] 

但是,如何通過提供用戶選項使這種動態更加動態?

在這一點上,我的用戶在FY提供布爾一些選項:

print ('What is the interested year?') 
print ('1. 2014') 
print ('2. 2015') 
print ('3. 2016') 

year = input('> ') 

if year == '1': 
    year1 = df['fy'] == '2014' 
elif year == '2': 
    year2 = df['fy'] == '2015' 

還有一些爲布爾區:

print ('What is the interested zone?') 
print ('1. AZW - Acquisition Zone West') 
print ('2. NAZ - Northern Acquisition Zone') 
print ('3. SAZ - Southern Acquisition Zone') 


zone = input('> ') 

if zone == '1': 
    zone1 = df['zones'] == 'AZW - Acquisition Zone West' 
elif zone == '2': 
    zone2 = df['zones'] == 'Northern Acquisition Zone' 

在這一點上,我不知道如何接收用戶選擇

newdf = df[choice1 & choice2] 

其中選擇1年和2選擇是區。

在此先感謝您的幫助!

回答

0

這是我的刺傷。您將需要爲錯誤輸入創建自己的錯誤消息和處理程序。

import pandas as pd 

df = pd.DataFrame({"PIID":[38542,33629,32789], 
        "fy":["2014","2015","2016"], 
        "zone":["AZW - Acquisition Zone West", "NAZ - Northern Acquisition Zone", "SAZ - Southern Acquisition Zone"]}) 


def get_choice(data, column): 
    """ 
    Gets user choice 
    """ 
    nums = [val for val in range(len(df[column].unique()))] 
    choices = list(zip(nums, df[column].unique())) 
    print("What '%s' would you like?\n" % column) 
    for v in choices: 
     print("%s. %s" % (v)) 
    user_input = input("Answer: ") 
    user_answer = [val[1] for val in choices if val[0]==int(user_input)][0] 
    print("'%s' = %s\n" % (column, user_answer)) # Just tells the user what they answered 
    return user_answer 

def main(): 

    year_input = get_choice(data=df, column="fy") 
    zone_input = get_choice(data=df, column="zone") 
    newdf = df.loc[(df["fy"]==year_input)&(df["zone"]==zone_input)] 
    print(newdf) 

if __name__ == "__main__": 
    main() 

所以,如果你輸入類似「0」爲第一個選項(年)和「0」的第二個選項(區)的輸出應該是這樣的:

PIID fy       zone 
0 38542 2014 AZW - Acquisition Zone West 

應該是規模,但正如我所說,你顯然必須添加自己的自定義調整。這應該足以讓你概括並解決問題中提出的問題。閱讀完代碼後,我建議您在工作中實施DRY原則(不要重複自己(例如,使用大量的if語句))。希望這可以幫助。

+0

謝謝,ralston!你釘了它。完全足以推廣。 – david