Hello there i have the following dataframe:
Name Lastname ticket
0 Peter Pan Ticket1
1 Null Null $20
i want to make it look like this:
Name Lastname ticket ticketprice
0 Peter Pan Ticket1 $20
1 NULL NULL Null Null
but it seems to be really difficult for me. Does anyone know how this works?
CodePudding user response:
Given that your odd columns contain the ticket price, one way you could do this is by copying the column into another ticketprice
column and shifting that column up by one like so:
import pandas as pd
df['ticket_price'] = df['ticket'].shift(-1)
df = df.iloc[::2]
Then delete all rows that have an even index to remove the empty line. In the example above df is the pandas dataframe containing your base data.
CodePudding user response:
Use loc to slice the frame into every other row and assign the value (assuming every other row is associated with the ticket price above).
Assuming this frame
Name Lastname ticket
0 Peter Pan Ticket1
1 Null Null $20
2 john doe ticket2
3 Null Null $30
then
import pandas as pd
import numpy as np
df.loc[0::2, 'ticketprice'] = df.iloc[1::2, 2].values
df.iloc[1::2] = np.nan
print(df)
Name Lastname ticket ticketprice
0 Peter Pan Ticket1 $20
1 NaN NaN NaN NaN
2 john doe ticket2 $30
3 NaN NaN NaN NaN