Ad
Pandas Dataframe To Dictionary With Conditions
I have this small dataframe:
PROCESS PROCEDURE SUB_PROCEDURE
---------------------------------
A NaN S1
B P1 S2
C P2 S3
D NaN S4
I would like to obtain a dictionary that, if the value in column 'PROCEDURE' is empty, the key, value pair consists of
PROCESS: SUB_PROCEDURE
and if there is something in the 'PROCEDURE' column:
'PROCESS' : {'PROCEDURE': SUB_PROCEDURE}.
This is how it would show for the above dataframe:
desired_output = {
'A': 'S1',
'B': {'P1': 'S2'},
'C': {'P1': 'S2'},
'D': 'S4'
}
This is what I've tried so far:
df_so.set_index('PROCESS')[['PROCEDURE', 'SUB_PROCEDURE']].to_dict()
Ad
Answer
Use dict comprehension with if
condition:
desired_output = {a: {b:c} if pd.notna(b) else c for a, b,c in df.to_numpy()}
print (desired_output)
{'A': 'S1', 'B': {'P1': 'S2'}, 'C': {'P2': 'S3'}, 'D': 'S4'}
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad