【问题标题】:ValueError: Wrong number of items in pandas dataframeValueError:熊猫数据框中的项目数量错误
【发布时间】:2021-07-13 19:12:52
【问题描述】:

我在运行以下函数时遇到错误 - ValueError: Wrong number of items passed 6, placement 意味着 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

我使用以下方法调用这些函数:

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

不知道这里出了什么问题。

【问题讨论】:

  • 实际上你的代码中有2个错误,第一个是关键错误,第二个是值错误
  • @AnuragDabas:对不起,你能解释一下吗?

标签: pandas valueerror


【解决方案1】:

函数encoding_1 返回整个数据框,您将其分配给原始数据框上的列。替换:

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

与:

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

【讨论】:

    猜你喜欢
    • 2020-02-10
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多