Filling DataFrame Pandas Python












1















I have a similar dataset, and even though the code gives me the right output; I do not want to use three for loops. Is there a way to do this in a better way?



import pandas as pd

col = ["a","b","c","d"]
index = ["0","1","2","3"]
dict_ = {("0","a"):8,
("1","a"):3,
("3","b"):2}

df = pd.DataFrame(columns=col,index=index)
for i in range(len(dict_)):
for j in range(len(df)):
for k in range(len(df)):
if (str(df.index[j]),str(df.columns[k])) == dict_.keys()[i]:
df.at[df.index[j],df.columns[k]] = dict_.values()[i]

print df









share|improve this question





























    1















    I have a similar dataset, and even though the code gives me the right output; I do not want to use three for loops. Is there a way to do this in a better way?



    import pandas as pd

    col = ["a","b","c","d"]
    index = ["0","1","2","3"]
    dict_ = {("0","a"):8,
    ("1","a"):3,
    ("3","b"):2}

    df = pd.DataFrame(columns=col,index=index)
    for i in range(len(dict_)):
    for j in range(len(df)):
    for k in range(len(df)):
    if (str(df.index[j]),str(df.columns[k])) == dict_.keys()[i]:
    df.at[df.index[j],df.columns[k]] = dict_.values()[i]

    print df









    share|improve this question



























      1












      1








      1








      I have a similar dataset, and even though the code gives me the right output; I do not want to use three for loops. Is there a way to do this in a better way?



      import pandas as pd

      col = ["a","b","c","d"]
      index = ["0","1","2","3"]
      dict_ = {("0","a"):8,
      ("1","a"):3,
      ("3","b"):2}

      df = pd.DataFrame(columns=col,index=index)
      for i in range(len(dict_)):
      for j in range(len(df)):
      for k in range(len(df)):
      if (str(df.index[j]),str(df.columns[k])) == dict_.keys()[i]:
      df.at[df.index[j],df.columns[k]] = dict_.values()[i]

      print df









      share|improve this question
















      I have a similar dataset, and even though the code gives me the right output; I do not want to use three for loops. Is there a way to do this in a better way?



      import pandas as pd

      col = ["a","b","c","d"]
      index = ["0","1","2","3"]
      dict_ = {("0","a"):8,
      ("1","a"):3,
      ("3","b"):2}

      df = pd.DataFrame(columns=col,index=index)
      for i in range(len(dict_)):
      for j in range(len(df)):
      for k in range(len(df)):
      if (str(df.index[j]),str(df.columns[k])) == dict_.keys()[i]:
      df.at[df.index[j],df.columns[k]] = dict_.values()[i]

      print df






      python pandas performance dataframe for-loop






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 '18 at 16:57









      Ken Dekalb

      321111




      321111










      asked Nov 23 '18 at 16:03









      Avantika BanerjeeAvantika Banerjee

      187




      187
























          1 Answer
          1






          active

          oldest

          votes


















          2














          IIUC, using reindex



          pd.Series(dict_).unstack().reindex(index=index,columns=col)
          Out[245]:
          a b c d
          0 8.0 NaN NaN NaN
          1 3.0 NaN NaN NaN
          2 NaN NaN NaN NaN
          3 NaN 2.0 NaN NaN





          share|improve this answer
























          • Beautiful! Thank you :')

            – Avantika Banerjee
            Nov 23 '18 at 16:12






          • 1





            @ W-B.. is always gives beautiful solution & tips :-) +1

            – pygo
            Nov 23 '18 at 16:13













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449792%2ffilling-dataframe-pandas-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          IIUC, using reindex



          pd.Series(dict_).unstack().reindex(index=index,columns=col)
          Out[245]:
          a b c d
          0 8.0 NaN NaN NaN
          1 3.0 NaN NaN NaN
          2 NaN NaN NaN NaN
          3 NaN 2.0 NaN NaN





          share|improve this answer
























          • Beautiful! Thank you :')

            – Avantika Banerjee
            Nov 23 '18 at 16:12






          • 1





            @ W-B.. is always gives beautiful solution & tips :-) +1

            – pygo
            Nov 23 '18 at 16:13


















          2














          IIUC, using reindex



          pd.Series(dict_).unstack().reindex(index=index,columns=col)
          Out[245]:
          a b c d
          0 8.0 NaN NaN NaN
          1 3.0 NaN NaN NaN
          2 NaN NaN NaN NaN
          3 NaN 2.0 NaN NaN





          share|improve this answer
























          • Beautiful! Thank you :')

            – Avantika Banerjee
            Nov 23 '18 at 16:12






          • 1





            @ W-B.. is always gives beautiful solution & tips :-) +1

            – pygo
            Nov 23 '18 at 16:13
















          2












          2








          2







          IIUC, using reindex



          pd.Series(dict_).unstack().reindex(index=index,columns=col)
          Out[245]:
          a b c d
          0 8.0 NaN NaN NaN
          1 3.0 NaN NaN NaN
          2 NaN NaN NaN NaN
          3 NaN 2.0 NaN NaN





          share|improve this answer













          IIUC, using reindex



          pd.Series(dict_).unstack().reindex(index=index,columns=col)
          Out[245]:
          a b c d
          0 8.0 NaN NaN NaN
          1 3.0 NaN NaN NaN
          2 NaN NaN NaN NaN
          3 NaN 2.0 NaN NaN






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 16:06









          W-BW-B

          105k73165




          105k73165













          • Beautiful! Thank you :')

            – Avantika Banerjee
            Nov 23 '18 at 16:12






          • 1





            @ W-B.. is always gives beautiful solution & tips :-) +1

            – pygo
            Nov 23 '18 at 16:13





















          • Beautiful! Thank you :')

            – Avantika Banerjee
            Nov 23 '18 at 16:12






          • 1





            @ W-B.. is always gives beautiful solution & tips :-) +1

            – pygo
            Nov 23 '18 at 16:13



















          Beautiful! Thank you :')

          – Avantika Banerjee
          Nov 23 '18 at 16:12





          Beautiful! Thank you :')

          – Avantika Banerjee
          Nov 23 '18 at 16:12




          1




          1





          @ W-B.. is always gives beautiful solution & tips :-) +1

          – pygo
          Nov 23 '18 at 16:13







          @ W-B.. is always gives beautiful solution & tips :-) +1

          – pygo
          Nov 23 '18 at 16:13




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449792%2ffilling-dataframe-pandas-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Berounka

          Sphinx de Gizeh

          Different font size/position of beamer's navigation symbols template's content depending on regular/plain...