Home > Back-end >  Python Reformat Dataframe
Python Reformat Dataframe

Time:12-31

I am trying to iterate through the dataframe and if the row's value Age column is empty, it will move the value in Name column to the Location column of the previous row. Is there a quick way to do this?

As-Is

As-Is Dataframe

To-Be

To-Be Dataframe

CodePudding user response:

You can use numpy:

arr = df.to_numpy()
arr[::2, -1] = arr[1::2,0]
df = pd.DataFrame(arr[::2], columns=df.columns)

Output:

      Name Age Location
0    Amber  21    North
1      Max  23    South
2  Jackson  38     East

CodePudding user response:

Here is a solution that works by iterating over the rows and copying the row's Name value to the previous row's Location value. Note this will break if the first row's Age is empty.

I'm pretty sure there's a more efficient way of dropping the empty rows at the end, so I welcome edits!

d = {'Name': ["Amber", "North", "Max", "South", "Jackson", "East"], 'Age': ["21", "", "23", "", "38", ""], "Location":["","","","","",""]}
df = pandas.DataFrame(data=d)

rows_to_drop = []

for index, values in df.iterrows():

    if not values["Age"]:

        df["Location"][index-1] = df["Name"][index]
        rows_to_drop.append(index)

df = df.drop(rows_to_drop)
  • Related