{"id":13934,"date":"2022-10-05T23:46:00","date_gmt":"2022-10-05T18:16:00","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/"},"modified":"2022-10-05T23:46:00","modified_gmt":"2022-10-05T18:16:00","slug":"solved-pandas-create-dynamic-columns-from-a-single-columns-values","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/","title":{"rendered":"[Solved] Pandas &#8211; Create dynamic column(s) from a single column&#8217;s values"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-69995246\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"69995246\" data-parentid=\"69943932\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>You could run one <code>apply()<\/code> which will use <code>for<\/code>-loop to convert list to  <code>Series<\/code> with headers &#8211; it can use <code>enumerate<\/code> to put correct number in headers.<\/p>\n<p>Because some rows have less participants so it puts <code>NaN<\/code> which you can later fill with empty strings.<\/p>\n<p>And next you can use <code>join()<\/code> to add all as new columns. Because headers are create in <code>apply()<\/code> so you don&#8217;t have to create them in <code>join()<\/code><\/p>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\n\ndata = {'participants': \n[\n    [{'roles': [{'type': 'director'}, {'type': 'founder'}, {'type': 'owner'}, {'type': 'real_owner'}], 'life': {'name': 'Lichun Du'}}],\n    [{'roles': [{'type': 'board'}], 'life': {'name': 'Erik M\u00f8lgaard'}}, {'roles': [{'type': 'director'}, {'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Mikael Bodholdt Linde'}}, {'roles': [{'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Dorte B\u00f8cker Linde'}}],\n    [{'roles': [{'type': 'director'}, {'type': 'real_owner'}], 'life': {'name': 'Kristian L\u00f8th Hougaard'}}, {'roles': [{'type': 'owner'}], 'life': {'name': 'WORLD JET HOLDING ApS'}}],\n]\n}\n\ndf = pd.DataFrame(data)\n\ndef get_names(cell):\n    \n    all_names = pd.Series(dtype=object)\n    \n    for number, item in enumerate(cell, 1):\n        name = item['life']['name']\n        all_names[f'Participant #{number} Name'] = name\n\n    return all_names\n\ndef get_roles(cell):\n    \n    all_roles = pd.Series(dtype=object)\n    \n    for number, item in enumerate(cell, 1):\n        roles = [role['type'] for role in item['roles']]\n        all_roles[f'Participant #{number} Role'] = \",\".join(roles)\n\n    return all_roles\n\nroles = df['participants'].apply(get_roles)\nroles = roles.fillna('')  # put empty string in place of NaN\n\nnames = df['participants'].apply(get_names)\nnames = names.fillna('')  # put empty string in place of NaN\n\ndf = df.join(roles)\ndf = df.join(names)\n\ndf = df.drop(columns=['participants'])  # remove old column\n\npd.options.display.max_colwidth = 100\nprint(df.to_string())\n<\/code><\/pre>\n<p>Result:<\/p>\n<pre><code>                 Participant #1 Role        Participant #2 Role Participant #3 Role     Participant #1 Name    Participant #2 Name Participant #3 Name\n0  director,founder,owner,real_owner                                                              Lichun Du                                           \n1                              board  director,board,real_owner    board,real_owner           Erik M\u00f8lgaard  Mikael Bodholdt Linde  Dorte B\u00f8cker Linde\n2                director,real_owner                      owner                      Kristian L\u00f8th Hougaard  WORLD JET HOLDING ApS  \n<\/code><\/pre>\n<hr>\n<p>I used two function to get first only columns with roles and next columns only with names &#8211; but if you would need <code>role1, name1, role2, name2, role3, name3<\/code> then it could be done with one function.<\/p>\n<pre><code>import pandas as pd\n\ndata = {'participants': \n[\n    [{'roles': [{'type': 'director'}, {'type': 'founder'}, {'type': 'owner'}, {'type': 'real_owner'}], 'life': {'name': 'Lichun Du'}}],\n    [{'roles': [{'type': 'board'}], 'life': {'name': 'Erik M\u00f8lgaard'}}, {'roles': [{'type': 'director'}, {'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Mikael Bodholdt Linde'}}, {'roles': [{'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Dorte B\u00f8cker Linde'}}],\n    [{'roles': [{'type': 'director'}, {'type': 'real_owner'}], 'life': {'name': 'Kristian L\u00f8th Hougaard'}}, {'roles': [{'type': 'owner'}], 'life': {'name': 'WORLD JET HOLDING ApS'}}],\n]\n}\n\ndf = pd.DataFrame(data)\n\ndef get_columns(cell):\n    \n    results = pd.Series(dtype=object)\n    \n    for number, item in enumerate(cell, 1):\n        name = item['life']['name']\n        results[f'Participant #{number} Name'] = name\n\n        roles = [role['type'] for role in item['roles']]\n        results[f'Participant #{number} Role'] = \",\".join(roles)\n\n    return results\n\ncolumns = df['participants'].apply(get_columns)\nnames = columns.fillna('')  # put empty string in place of NaN\n\ndf = df.join(columns)\n#print(df.columns)\n\ndf = df.drop(columns=['participants'])\n\npd.options.display.max_colwidth = 100\nprint(df.to_string())\n<\/code><\/pre>\n<p>Result:<\/p>\n<pre><code>      Participant #1 Name                Participant #1 Role    Participant #2 Name        Participant #2 Role Participant #3 Name Participant #3 Role\n0               Lichun Du  director,founder,owner,real_owner                    NaN                        NaN                 NaN                 NaN\n1           Erik M\u00f8lgaard                              board  Mikael Bodholdt Linde  director,board,real_owner  Dorte B\u00f8cker Linde    board,real_owner\n2  Kristian L\u00f8th Hougaard                director,real_owner  WORLD JET HOLDING ApS                      owner                 NaN                 NaN\n<\/code><\/pre>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">11<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Pandas &#8211; Create dynamic column(s) from a single column&#8217;s values <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] You could run one apply() which will use for-loop to convert list to Series with headers &#8211; it can use enumerate to put correct number in headers. Because some rows have less participants so it puts NaN which you can later fill with empty strings. And next you can use join() to add all &#8230; <a title=\"[Solved] Pandas &#8211; Create dynamic column(s) from a single column&#8217;s values\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/\" aria-label=\"More on [Solved] Pandas &#8211; Create dynamic column(s) from a single column&#8217;s values\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[461,415,928,349],"class_list":["post-13934","post","type-post","status-publish","format-standard","hentry","category-solved","tag-dataframe","tag-pandas","tag-pandas-groupby","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Pandas - Create dynamic column(s) from a single column&#039;s values - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Pandas - Create dynamic column(s) from a single column&#039;s values - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] You could run one apply() which will use for-loop to convert list to Series with headers &#8211; it can use enumerate to put correct number in headers. Because some rows have less participants so it puts NaN which you can later fill with empty strings. And next you can use join() to add all ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-10-05T18:16:00+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Pandas &#8211; Create dynamic column(s) from a single column&#8217;s values\",\"datePublished\":\"2022-10-05T18:16:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/\"},\"wordCount\":127,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"dataframe\",\"pandas\",\"pandas-groupby\",\"python\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/\",\"name\":\"[Solved] Pandas - Create dynamic column(s) from a single column's values - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-10-05T18:16:00+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Pandas &#8211; Create dynamic column(s) from a single column&#8217;s values\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Pandas - Create dynamic column(s) from a single column's values - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Pandas - Create dynamic column(s) from a single column's values - JassWeb","og_description":"[ad_1] You could run one apply() which will use for-loop to convert list to Series with headers &#8211; it can use enumerate to put correct number in headers. Because some rows have less participants so it puts NaN which you can later fill with empty strings. And next you can use join() to add all ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/","og_site_name":"JassWeb","article_published_time":"2022-10-05T18:16:00+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Pandas &#8211; Create dynamic column(s) from a single column&#8217;s values","datePublished":"2022-10-05T18:16:00+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/"},"wordCount":127,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["dataframe","pandas","pandas-groupby","python"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/","url":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/","name":"[Solved] Pandas - Create dynamic column(s) from a single column's values - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-10-05T18:16:00+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-pandas-create-dynamic-columns-from-a-single-columns-values\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Pandas &#8211; Create dynamic column(s) from a single column&#8217;s values"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/13934","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=13934"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/13934\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=13934"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=13934"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=13934"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}