gpt4 book ai didi

Python DatetimeIndex 错误 - TypeError : ("cannot do label indexing on
转载 作者:太空狗 更新时间:2023-10-30 02:29:47 26 4
gpt4 key购买 nike

到目前为止,我有 EdChum 提供的以下代码:

In [1]:
df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3, 10, 3, 5, 8]})
df["c"] =np.NaN

df["c"][0] = 1
df["c"][2] = 3


def func(x):
if pd.notnull(x['c']):
return x['c']
else:
return df.iloc[x.name - 1]['c'] * x['b']
df['c'] = df.apply(func, axis =1)
df['c'] = df.apply(func, axis =1)
df['c'] = df.apply(func, axis =1)
df

Out[1]:
a b c
0 None 2 1
1 None 3 3
2 None 10 3
3 None 3 9
4 None 5 45
5 None 8 360

这也很好用,但是只要我按如下方式更改 dateframe = df 的索引:

rng = pd.date_range('1/1/2011', periods=6, freq='D')

df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3, 10, 3, 5, 8]},index=rng)

我收到以下错误:TypeError: ("cannot do label indexing on <class 'pandas.tseries.index.DatetimeIndex'> with these indexers [2011-01-01 00:00:00] of <class 'pandas.tslib.Timestamp'>", u'occurred at index 2011-01-02 00:00:00')

这里有什么问题?我需要如何调整代码才能使其与 da DatetimeIndex 一起使用?

最佳答案

以下工作,这里的区别是我使用 get_loc 获取索引中日期时间值的整数位置:

In [48]:

rng = pd.date_range('1/1/2011', periods=6, freq='D')
df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3, 10, 3, 5, 8]},index=rng)
df["c"] =np.NaN

df["c"][0] = 1
df["c"][2] = 3


def func(x):
if pd.notnull(x['c']):
return x['c']
else:
return df.iloc[df.index.get_loc(x.name) - 1]['c'] * x['b']
df['c'] = df.apply(func, axis =1)
df['c'] = df.apply(func, axis =1)
df['c'] = df.apply(func, axis =1)
df

Out[48]:
a b c
2011-01-01 None 2 1
2011-01-02 None 3 3
2011-01-03 None 10 3
2011-01-04 None 3 9
2011-01-05 None 5 45
2011-01-06 None 8 360

关于Python DatetimeIndex 错误 - TypeError : ("cannot do label indexing on <class ' pandas. tseries.index.DatetimeIndex',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30676186/

26 4 0

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