Search code examples
pandasvalueerror

ValueError: Wrong number of items in pandas dataframe


I get the error while running the below functions - ValueError: Wrong number of items passed 6, placement implies 1.

def encoding(df, column_name: str):
  if column_name in df.columns:
    dr = df[column_name].values
    df['Week Day'] = pd.to_datetime(dr).weekday
    df['Month'] = pd.DatetimeIndex(df[column_name]).month
  df['feature_week_day'] = encoding_1(df,'Week Day',7)
  df['feature_month'] = encoding_1(df,'Month', 12)
  return df

def encoding_1(df, column_name: str, period: int):
  if column_name in df.columns:
    df['sine_' + column_name] = np.sin(2 * np.pi * df[column_name] / period)
    df['cosine_' + column_name] = np.cos(2 * np.pi * df[column_name] / period)
  return df

I call these functions using:

df = pd.DataFrame({'Id':['ABC123', 'ABC124', 'ABC125', 'ABC126'], 'Date':['2008-01-01','2008-01-02','2020-02-01', '20210419']})
result = encoding(df,'Date')

Not sure what's wrong here.


Solution

  • The function encoding_1 return an entire dataframe and you are assigning it to a column on the original dataframe. Replace:

    # ...
    df['feature_week_day'] = encoding_1(df,'Week Day',7)
    df['feature_month'] = encoding_1(df,'Month', 12)
    # ...
    

    with:

    # ...
    df = encoding_1(df,'Week Day',7)
    df = encoding_1(df,'Month', 12)
    # ...