在数据帧中设置多条件列时出错

2024-05-14 10:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是下载一个excel报告并将其转换为一个数据框架,然后根据现有的列信息创建一些列。我以前没有遇到过问题,但现在出现以下错误:

ValueError: cannot set using a multi-index selection indexer with a different length than the value

下面是一个代码示例。错误发生在第一行:

df.loc[df['Blank'] != 'ENDING MY','Month'] = pd.DatetimeIndex(df['Date']).month
df.loc[(df['Blank'] == 'ENDING MY') & (df['Commodity'] == 'All Upland Cotton'),'Month'] = 7
df.loc[(df['Blank'] == 'ENDING MY') & (df['Commodity'] == 'All Wheat'),'Month'] = 5
df.loc[(df['Blank'] == 'ENDING MY') & (df['Commodity'] == 'Corn'),'Month'] = 8
df.loc[(df['Blank'] == 'ENDING MY') & (df['Commodity'] == 'Soybeans'),'Month'] = 8
df.loc[(df['Blank'] == 'ENDING MY') & (df['Commodity'] == 'Sorghum'),'Month'] = 8

“空白”列中只有三个潜在变量:它是空的、开始我的或结束我的。这个特殊的数据拉取既有结束MY,也有开始MY,这可能与我测试它时不同

但是,由于代码在第一行输出错误,因此两个选项分别为“开始我的”和“空白”。在我们使用blank并没有启动我的之前,我尝试了一行代码,这只是:

df.loc[df['Blank'] == 'STARTING MY','Month'] = pd.DatetimeIndex(df['Date']).month

该行再次出现错误

有人知道它为什么会导致这个问题吗?我能做些什么来解决它

dataframe中的示例列:**是列名。将计算月列。在这种情况下,大豆也应该是第8个月

**Commodity** **Blank** **Value1** **Value 2** **Value 3** **Date**    **Month**
All Wheat                   1           3          4       2020-08-17      8
All Wheat                   4           4          2       2020-08-17      8
Corn                        1           12         5       2020-08-17      8
Corn                        4           24         5       2020-08-17      8
Soybeans      ENDING MY     2           34         24      2020-08-17      8
Soybeans      ENDING MY     34          2          34      2020-08-17      8
Sorghum       STARTING MY   4           45         3       2020-08-17      8
Sorghum       STARTING MY   4           34         4       2020-08-17      8

Tags: 代码dfdatemy错误endingallloc
1条回答
网友
1楼 · 发布于 2024-05-14 10:28:36

IIUC,您需要这样做,首先将Date列转换为datetime,然后设置值:

df['Date'] = pd.to_datetime(df['Date'])
df.loc[df['Blank'] == 'STARTING MY','Month'] = df['Date'].dt.month
print(df)

   Commodity        Blank  Value1  Value 2  Value 3       Date  Month
0  All Wheat          NaN       1        3        4 2020-08-17    NaN
1  All Wheat          NaN       4        4        2 2020-08-17    NaN
2       Corn          NaN       1       12        5 2020-08-17    NaN
3       Corn          NaN       4       24        5 2020-08-17    NaN
4   Soybeans    ENDING MY       2       34       24 2020-08-17    NaN
5   Soybeans    ENDING MY      34        2       34 2020-08-17    NaN
6    Sorghum  STARTING MY       4       45        3 2020-08-17    8.0
7    Sorghum  STARTING MY       4       34        4 2020-08-17    8.0

相关问题 更多 >

    热门问题