我的代码是下载一个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
在“空白”列中只有三个潜在的变量:它是空的、开始我的或结束我的。这个特定的数据拉取既有我的结尾,也有我的开头,这可能与我测试它时不同。
但是,由于代码在第一行输出了一个错误,因此有两个选项分别为STARTING和blank。之前我们有空白,没有开始我的,所以我尝试了这之前的一行代码,这是简单的:
df.loc[df['Blank'] == 'STARTING MY','Month'] = pd.DatetimeIndex(df['Date']).month
错误又抛到了那一行上。
有谁知道为什么它会导致这个问题,我能做些什么来解决它?
来自dataframe的示例列:**是列名。将计算month列。在这种情况下,大豆也应该是第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
发布于 2020-08-17 22:41:59
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
https://stackoverflow.com/questions/63451497
复制相似问题