Skip to main content
 首页 » 编程设计

python之使用 numpy 根据多个 where 条件更新数据框值

2024年10月01日7mayingbao

我要改DateWork['Variable']根据多个 where 条件的值并在 DateWork['Date'] 中更新

如果Frequency=3和 len(Variable)=6然后将 M 替换为“-0”并在 DateWork['Date'] 中更新 如果Frequency=3和 len(Variable)=7然后将 M 替换为“-”并在 DateWork['Date'] 中更新

数据框架:数据工作

Frequency Variable      Date 
3         1950M2        1950-02-01 
3         1950M3        1950-03-01 
2         1950-07-01    1950-07-01 
3         1950M9        1950-09-01 
2         1950-10-01    1950-10-01 
3         1950M10       1950-10-01 

我的代码:

DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 6)), 'M', '-0',  DateWork['Date']) 
DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 7)), 'M', '-',  DateWork['Date']) 
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'variable'] + '-01' 

这给出了错误:

TypeError: where() takes at most 3 arguments (4 given)

请您参考如下方法:

你的错误是因为你传递了一个额外的参数给np.where,你可以查看关于这个方法的文档,链接如下。还有一次,这个问题得到解决,您编写代码的方式使最后一个 np.where 调用更新并替换之前的所有代码,因此它们需要“嵌套”才能正常工作。

如果您需要,我还提供了一个没有 np.where 的解决方案。

解决方案 numpy.where :

# where frequenct == 3 and len(variable) == 6, we put variable and replace M with -0, if that's not 
# the case, we search where frequency == 3 and len(variable) == 7 and put variable while replacing M with - 
# else we just put Variable 
DateWork['Date'] = np.where((DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 6), DateWork['Variable'].str.replace('M','-0'), 
                       np.where((DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 7), DateWork['Variable'].str.replace('M','-'), DateWork['Variable'])) 
 
# we add first day date where frequency == 3 
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'Date'] + '-01' 

解决方案 pandas.dataframe.loc :

# where frenquency == 3 and len(variable) == 6, in date we put variable and replace M with -0 
DateWork.loc[(DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 6),'Date'] = DateWork['Variable'].str.replace('M','-0') 
 
# where frequency == 3 and len(variable) == 7, in date we put variable and replace M with - 
DateWork.loc[(DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 7),'Date'] = DateWork['Variable'].str.replace('M','-') 
 
# where frequency == 2, in date we simply put variable 
DateWork.loc[DateWork['Frequency'] == 2,'Date'] = DateWork['Variable'] 
 
# where frequency == 3, in date we add first day date. 
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'Date'] + '-01'