Reputation: 1355
I am working with Python Pandas & I have the below use-case -
I am using a parameter dictionary to accept user inputs & I have an input variable "Period" with a user value 10.
paramDict = {
"Period":
{
"Description": "A Period to filter on.",
"ParameterType" : "Value",
"DataType": "Number",
"Value" : ['10']
}
}
Now, I have a dataframe df_temp as below -
CODE POSTING_PERIOD POSTING_VALUE
0 00152 CDD01J 115084
1 00152 CDD02J 115177
2 00152 CDD03J 115271
3 00152 CDD04J 115359
4 00152 CDD05J 115359
5 00152 CDD06J 115359
6 00152 CDD07J 115359
7 00152 CDD08J 115359
8 00152 CDD09J 115359
9 00152 CDD10J 115359
10 00152 CDD11J 115359
11 00152 CDD12J 115359
Now, based on the user input "10" in this case, I want only row 9 to be selected where df['POSTING_PERIOD'] = 'CDD10J'
Note: In case the user input is 1, we should be able to prefix 0 to 1 & then row 0 should be selected where df['POSTING_PERIOD'] = 'CDD01J'
Can you please help me on the same? Thanks
Upvotes: 0
Views: 71
Reputation: 10960
Extending @joris code:
> user_input = paramDict['Period']['Value']
> df_temp[df_temp['POSTING_PERIOD'].str[3:5].astype(int) == int(user_input)]
CODE POSTING_PERIOD POSTING_VALUE
0 152 CDD01J 115084
Upvotes: 1
Reputation: 265
EDIT: Upon further reflection simply use zfill to pad the string to length 2 zfill will turn a string into a string of specific length with padded zeros:
In [1]: '1'.zfill(2)
Out [1]: '01'
In [2]: '12'.zfill(2)
Out [2]: '12'
You can use standard string methods to grab a portion of the dataframe. Here that would look like
df_temp[df_temp.POSTING_PERIOD.str.contains(paramDict['Period']['Value'].zfill(2))]
Upvotes: 1