Python Forum
Negative indexing/selecting working and not working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Negative indexing/selecting working and not working
#16
You should start with 1 question.
import pandas as pd

df = pd.DataFrame(
    [
        {"type": "Strongly disagree", "value": 24},
        {"type": "Disagree", "value": 294},
        {"type": "Neither agree nor disagree", "value": 594},
        {"type": "Agree", "value": 1927},
        {"type": "Strongly agree", "value": 376},
    ]
)

df["type_code"] = df.type.map(
    {
        "Strongly disagree": -2,
        "Disagree": -1,
        "Neither agree nor disagree": 0,
        "Agree": 1,
        "Strongly agree": 2,
    }
)

df = df.set_index("type_code").sort_index()

perc = (df["value"] / df["value"].sum()) * 100
df["percentage"] = perc

perc = df["percentage"]
df["percentage_end"] = perc.cumsum() - (perc[-2] + perc[-1] + perc[0] / 2)

perc = df["percentage"]
df["percentage_start"] = df["percentage_end"] - perc

df = df.reset_index(drop=True)

print(df)
Output:
type value percentage percentage_end percentage_start 0 Strongly disagree 24 0.746501 -18.382582 -19.129082 1 Disagree 294 9.144635 -9.237947 -18.382582 2 Neither agree nor disagree 594 18.475894 9.237947 -9.237947 3 Agree 1927 59.937792 69.175739 9.237947 4 Strongly agree 376 11.695179 80.870918 69.175739
Grouping and using the apply function on groups is fairly advanced pandas. Save that for later.
Reply


Messages In This Thread
RE: Negative indexing/selecting working and not working - by deanhystad - Jul-13-2023, 05:34 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Gmpy2 Newbie Working on Precision charlesrkiss 6 733 Yesterday, 09:53 AM
Last Post: sunflower36002
  Working with group of lines knob 1 300 May-21-2024, 07:21 AM
Last Post: Gribouillis
  two functions working in a strange way zapad 2 388 May-02-2024, 01:35 PM
Last Post: zapad
  Excel isnt working properly after python function is started IchNar 2 438 May-01-2024, 06:43 PM
Last Post: IchNar
  negative memory usage akbarza 1 368 Apr-27-2024, 08:43 AM
Last Post: Gribouillis
  Python trivial endgame engine is not working as expected max22 0 637 Feb-24-2024, 04:41 PM
Last Post: max22
  File Handling not working properly TheLummen 8 1,057 Feb-17-2024, 07:47 PM
Last Post: TheLummen
  Spyder console zoom in not working? Dionysis 2 573 Feb-06-2024, 03:31 PM
Last Post: paul18fr
  SendKeys not working SanjayGMusafir 4 672 Jan-16-2024, 12:07 PM
Last Post: EdwardMatthew
  Text conversion to lowercase is not working ineuw 3 606 Jan-16-2024, 02:42 AM
Last Post: ineuw

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020