Home > Blockchain >  How to replace one column name with multiple column names in existing pandas dataframe?
How to replace one column name with multiple column names in existing pandas dataframe?

Time:10-29

I have a dataframe that looks like this: print(df)

0
0 01-Dec 92 1,475.60 0.00
1 02-Dec 106 0.00 0.00
3 03-Dec 0.00 75.00

I would like to be able to get my dataframe to look like this (add in the column names and shift the 3rd row to the left):

Process_Date Transactions Net_Sales Third_Party
0 01-Dec 92 1,475.60 0.00
1 02-Dec 106 0.00 0.00
3 03-Dec 0.00 75.00 0.00

This is my code to add in the column names:

df.columns = ["Process_Date", "Transactions", "Net_Sales", "Third_Party"]

def shifter(row):
    return np.hstack((delete(np.array(row), [1]), [np.nan]))

mask = df['Transactions'] == '03-Dec'
df.loc[mask, :] = df.loc[mask, :].apply(shift, axis=1)

This is the Output:

ValueError: Length mismatch: Expected axis has 1 elements, new values have 4 elements

CodePudding user response:

here is one way to do it

# filter the rows, as per your question
mask = df['Transactions'] == '03-Dec'

# shift the values left along the axis (row), and fill NaN with zero
df.loc[mask]=df.loc[mask].shift(-1,axis=1).fillna(0, axis=1)
df
    Process_Date    Transactions    Net_Sales   Third_Party
0   01-Dec                 92        1,475.60         0.0
1   02-Dec                106            0.00         0.0
3   03-Dec                  0.00        75.0          0

  • Related