gpt4 book ai didi

python - Pandas:必须传递带有 bool 值的 DataFrame,仅用作 asfreq

转载 作者:行者123 更新时间:2023-12-01 02:04:51 26 4
gpt4 key购买 nike

我有以下代码,它给了我非常奇怪的错误,我的目标是回填具有不同标签的数据的缺失值。如果我更改 df_filled=df.asfreq(freq='D').fillna(method='bfill', limit=1),则此行 df_filled[is_filled] 会发生错误。 dropna(how='all').drop_duplicates(keep='last') 一切正常,但使用 freq=2D 时,df_filled[is_filled] 没有 bool 形式。

    from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import random
##Generate the Data
np.random.seed(11)
date_today = datetime.now()
ndays = 15
df = pd.DataFrame({'date': [date_today + timedelta(days=(abs(np.random.randn(1))*2)[0]*x) for x in range(ndays)],
'test': pd.Series(np.random.randn(ndays)), 'test2':pd.Series(np.random.randn(ndays))})
df1=pd.DataFrame({'date': [date_today + timedelta(hours=x) for x in range(ndays)],
'test': pd.Series(np.random.randn(ndays)), 'test2':pd.Series(np.random.randn(ndays))})
df2=pd.DataFrame({'date': [date_today + timedelta(days=x)-timedelta(seconds=100*x) for x in range(ndays)],
'test': pd.Series(np.random.randn(ndays)), 'test2':pd.Series(np.random.randn(ndays))})
df=df.append(df1)
df=df.append(df2)
df = df.set_index('date').sort_index()
df = df.mask(np.random.random(df.shape) < .7)
df=df.reset_index()
df['test']=df['test'].astype(str)
df['test2']=df['test2'].astype(str)
df.replace('nan', np.nan, inplace = True)
##

df.set_index(df['date'].dt.date, inplace = True)

df = df[~df.index.duplicated(keep='first')]
df_filled=df.asfreq(freq='2D').fillna(method='bfill', limit=2).dropna(how='all').drop_duplicates(keep='last')
df_filled.set_index(df_filled['date'],inplace=True)
df_filled=df_filled.drop('date',1)
df.set_index(df['date'],inplace=True)
df=df.drop('date',1)
is_filled = (df.isnull() & df_filled.notnull()) | df.notnull()
df_filled[is_filled] ## error happens here
df_filled[is_filled]=df_filled[is_filled].applymap(lambda x: '_2D' if pd.notnull(x) else np.nan)

输出:ValueError:必须仅传递带有 bool 值的 DataFrame

非常感谢您提前提供的帮助。

最佳答案

如果你 print(is_filled = (df.isnull() & df_filled.notnull()) | df.notnull()) 那么你会看到你有 True 的混合NaN。因此,解决方案是将 NaN 值替换为 False:

底部代码片段:

df=df.drop('date',1)
is_filled = (df.isnull() & df_filled.notnull()) | df.notnull()
is_filled = is_filled.fillna(False) # Fix here
df_filled[is_filled]=df_filled[is_filled].applymap(lambda x: '_2D' if pd.notnull(x) else np.nan)

关于python - Pandas:必须传递带有 bool 值的 DataFrame,仅用作 asfreq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49184201/

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