After transferring from float type to int type, why the number all altered into -1 in python?How do I parse a string to a float or int in Python?How do I determine the size of an object in Python?Peak detection in a 2D arrayWhy is reading lines from stdin much slower in C++ than Python?Converting a Pandas GroupBy object to DataFrameAdding new column to existing DataFrame in Python pandas“Large data” work flows using pandasAdd new column in pandas data frameNumpy turning ints to decimalsDifferent results from syntax

How does one intimidate enemies without having the capacity for violence?

Why can't I see bouncing of a switch on an oscilloscope?

Why are electrically insulating heatsinks so rare? Is it just cost?

Minkowski space

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

Why do I get two different answers for this counting problem?

Writing rule stating superpower from different root cause is bad writing

Is this a crack on the carbon frame?

What would happen to a modern skyscraper if it rains micro blackholes?

Show that if two triangles built on parallel lines, with equal bases have the same perimeter only if they are congruent.

Why do falling prices hurt debtors?

Do VLANs within a subnet need to have their own subnet for router on a stick?

What does it mean to describe someone as a butt steak?

Approximately how much travel time was saved by the opening of the Suez Canal in 1869?

Theorem, big Paralist and Amsart

Smoothness of finite-dimensional functional calculus

What do the dots in this tr command do: tr .............A-Z A-ZA-Z <<< "JVPQBOV" (with 13 dots)

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

TGV timetables / schedules?

Problem of parity - Can we draw a closed path made up of 20 line segments...

What defenses are there against being summoned by the Gate spell?

Can divisibility rules for digits be generalized to sum of digits

Modeling an IPv4 Address

"You are your self first supporter", a more proper way to say it



After transferring from float type to int type, why the number all altered into -1 in python?


How do I parse a string to a float or int in Python?How do I determine the size of an object in Python?Peak detection in a 2D arrayWhy is reading lines from stdin much slower in C++ than Python?Converting a Pandas GroupBy object to DataFrameAdding new column to existing DataFrame in Python pandas“Large data” work flows using pandasAdd new column in pandas data frameNumpy turning ints to decimalsDifferent results from syntax






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















This is the code I entered:



df = pd.DataFrame('A': [1.6,1.2,3.9,4.5, np.nan]) 
df['A'] = df['A'].fillna(-1).astype(int)
for i in df['A']:
df["B"] = i
df


But the result I get is like this:



enter image description here



So why the column B would all appear as -1 instead of the same as column A?










share|improve this question



















  • 2





    Please add the output in code format, not in image.

    – pistol2myhead
    Mar 8 at 4:36

















0















This is the code I entered:



df = pd.DataFrame('A': [1.6,1.2,3.9,4.5, np.nan]) 
df['A'] = df['A'].fillna(-1).astype(int)
for i in df['A']:
df["B"] = i
df


But the result I get is like this:



enter image description here



So why the column B would all appear as -1 instead of the same as column A?










share|improve this question



















  • 2





    Please add the output in code format, not in image.

    – pistol2myhead
    Mar 8 at 4:36













0












0








0








This is the code I entered:



df = pd.DataFrame('A': [1.6,1.2,3.9,4.5, np.nan]) 
df['A'] = df['A'].fillna(-1).astype(int)
for i in df['A']:
df["B"] = i
df


But the result I get is like this:



enter image description here



So why the column B would all appear as -1 instead of the same as column A?










share|improve this question
















This is the code I entered:



df = pd.DataFrame('A': [1.6,1.2,3.9,4.5, np.nan]) 
df['A'] = df['A'].fillna(-1).astype(int)
for i in df['A']:
df["B"] = i
df


But the result I get is like this:



enter image description here



So why the column B would all appear as -1 instead of the same as column A?







python pandas numpy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 4:44









Spencer Wieczorek

17.6k43345




17.6k43345










asked Mar 8 at 4:35









RachelRachel

6




6







  • 2





    Please add the output in code format, not in image.

    – pistol2myhead
    Mar 8 at 4:36












  • 2





    Please add the output in code format, not in image.

    – pistol2myhead
    Mar 8 at 4:36







2




2





Please add the output in code format, not in image.

– pistol2myhead
Mar 8 at 4:36





Please add the output in code format, not in image.

– pistol2myhead
Mar 8 at 4:36












3 Answers
3






active

oldest

votes


















2














You are setting the entire column to i with df["B"] = i. In your last iteration, i is -1, so your entire column B is set to -1.



If you want to set B to A, you can just use this (no for loop needed):



df['B'] = df['A']





share|improve this answer






























    0














    In your for loop you reassign the entire value of df["B"] each time. The last value in df['A'] (np.nan) when converted to a int is -1. Since you are setting df["B"] as a whole all the value are assigned as -1.






    share|improve this answer






























      0














      Change



      for i in df['A']:
      df["B"] = i


      to



      for i, item in df['A'].items():
      df.ix[i, "B"] = item





      share|improve this answer























        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%2f55056791%2fafter-transferring-from-float-type-to-int-type-why-the-number-all-altered-into%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        You are setting the entire column to i with df["B"] = i. In your last iteration, i is -1, so your entire column B is set to -1.



        If you want to set B to A, you can just use this (no for loop needed):



        df['B'] = df['A']





        share|improve this answer



























          2














          You are setting the entire column to i with df["B"] = i. In your last iteration, i is -1, so your entire column B is set to -1.



          If you want to set B to A, you can just use this (no for loop needed):



          df['B'] = df['A']





          share|improve this answer

























            2












            2








            2







            You are setting the entire column to i with df["B"] = i. In your last iteration, i is -1, so your entire column B is set to -1.



            If you want to set B to A, you can just use this (no for loop needed):



            df['B'] = df['A']





            share|improve this answer













            You are setting the entire column to i with df["B"] = i. In your last iteration, i is -1, so your entire column B is set to -1.



            If you want to set B to A, you can just use this (no for loop needed):



            df['B'] = df['A']






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 8 at 4:41









            busybearbusybear

            3,71011027




            3,71011027























                0














                In your for loop you reassign the entire value of df["B"] each time. The last value in df['A'] (np.nan) when converted to a int is -1. Since you are setting df["B"] as a whole all the value are assigned as -1.






                share|improve this answer



























                  0














                  In your for loop you reassign the entire value of df["B"] each time. The last value in df['A'] (np.nan) when converted to a int is -1. Since you are setting df["B"] as a whole all the value are assigned as -1.






                  share|improve this answer

























                    0












                    0








                    0







                    In your for loop you reassign the entire value of df["B"] each time. The last value in df['A'] (np.nan) when converted to a int is -1. Since you are setting df["B"] as a whole all the value are assigned as -1.






                    share|improve this answer













                    In your for loop you reassign the entire value of df["B"] each time. The last value in df['A'] (np.nan) when converted to a int is -1. Since you are setting df["B"] as a whole all the value are assigned as -1.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 8 at 4:42









                    Spencer WieczorekSpencer Wieczorek

                    17.6k43345




                    17.6k43345





















                        0














                        Change



                        for i in df['A']:
                        df["B"] = i


                        to



                        for i, item in df['A'].items():
                        df.ix[i, "B"] = item





                        share|improve this answer



























                          0














                          Change



                          for i in df['A']:
                          df["B"] = i


                          to



                          for i, item in df['A'].items():
                          df.ix[i, "B"] = item





                          share|improve this answer

























                            0












                            0








                            0







                            Change



                            for i in df['A']:
                            df["B"] = i


                            to



                            for i, item in df['A'].items():
                            df.ix[i, "B"] = item





                            share|improve this answer













                            Change



                            for i in df['A']:
                            df["B"] = i


                            to



                            for i, item in df['A'].items():
                            df.ix[i, "B"] = item






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 8 at 7:21









                            hacker315hacker315

                            563213




                            563213



























                                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%2f55056791%2fafter-transferring-from-float-type-to-int-type-why-the-number-all-altered-into%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

                                Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved