首页 > 解决方案 > How to get the user Input in Pandas for a particular column from the dataframe python3

问题描述

I'm using PANDAS Dataframe to get the data from CSV file and opting to choose the desired column data which is working fine. However, in the hostData Dataframe i'm looking specially for (data['Safe']=='KDS-PDC-DEFAULT-UNIX-ROOT') portion so, as i have multiple safes as i mentioned below the CyberArk Safes within the doc string hence i'm looking forward to rather putting the safe name manually on the code it could ask on the user input.

While asking for the User Input to give the safe name if it could display the current safe names which is within doc string.

#!/grid/common/pkgs/python/v3.6.1/bin/python3
from __future__ import print_function
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
import csv
import pandas as pd

##### Python pandas, widen output display to see more columns. ####
pd.set_option('display.height', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('expand_frame_repr', True)

############# CyberArk Safes ################
'''  
KDS-KDC-DEFAULT-UNIX-ROOT
KDS-PDC-DEFAULT-UNIX-ROOT
KDS-CDC-DEFAULT-UNIX-ROOT
'''

################# PANDAS Extraction ###########
data = pd.read_csv('/home/karn/plura/Test/Python_Panda/InventoryReports06.csv', usecols=['Platform ID', 'Safe', 'Target system address', 'Failure reason'])
hostData = data[(data['Safe']=='DC') | (data['Safe']=='KDS-PDC-DEFAULT-UNIX-ROOT')][['Safe', 'Target system address']]
hostData.reset_index(level=0, drop=True)

Expected Output:

$ python CyberSafe.py
 The Current SafeName Available are:
 KDS-KDC-DEFAULT-UNIX-ROOT
 KDS-PDC-DEFAULT-UNIX-ROOT
 KDS-CDC-DEFAULT-UNIX-ROOT

 Please Enter the SafeName: 

Any help or suggestion will highly be appreciated.

标签: pythonpandasdataframeinputdocstring

解决方案


  1. For displaying candidates, create a function (e.g. print_candidates()) to show a docstring.
  2. For getting user inputs, use input() and store it to SafeName and further use it to create a mask to filter the dataframe.

Therefore the later part of your code would be something like below:

def print_candidates():
    '''  
    KDS-KDC-DEFAULT-UNIX-ROOT
    KDS-PDC-DEFAULT-UNIX-ROOT
    KDS-CDC-DEFAULT-UNIX-ROOT
    '''
    print("The Current SafeName Available are:")
    print(print_candidates.__doc__)

print_candidates()

################# PANDAS Extraction ###########
data = pd.read_csv('/home/karn/plura/Test/Python_Panda/InventoryReports06.csv', usecols=['Platform ID', 'Safe', 'Target system address', 'Failure reason'])
SafeName = str(input("Please Enter the SafeName:"))
hostData = data.loc[(data['Safe']=='DC') | (data['Safe']==SafeName)][['Safe', 'Target system address']]
hostData = hostData.reset_index(drop=True)

推荐阅读