gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:32 24 4
gpt4 key购买 nike

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

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

关于python - 使用 numpy 根据多个 where 条件更新数据框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44995737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com