gpt4 book ai didi

python - Keyerror 多索引数据框 pandas

转载 作者:行者123 更新时间:2023-11-30 08:31:38 25 4
gpt4 key购买 nike

我有一个数据框(称为错误),如下所示:

Code                         ID                Error1     Error 2
Time
2010-01-01 00:00:31.690 105278.0 None 5
2010-01-01 00:00:32.000 105278.0 1 None
2010-01-01 00:00:32.140 105278.0 3 None
2010-01-01 00:00:32.350 105278.0 None 7
2010-01-01 00:00:32.460 105278.0 None 1

我想计算每个时间戳的不同类型的错误并将它们保存在单独的列中:

 error_count =
pd.get_dummies(errors.set_index('Time')).reset_index()
error_count.columns = ['Time', 'machineID', 'error1', 'error2',
'error3', 'error4', 'error5']

# combine errors for a given machine in a given hour error_count = error_count.groupby(['machineID', 'datetime']).sum().reset_index()

我有两个问题,第一是:当我运行时

pd.get_dummies(errors.set_index('Time')).reset_index()

我收到 key 错误(KeyError:'Time')

第二个问题是我不知道我的错误中会出现多少不同的代码(Error1和Error 2),所以我不确定如何编写

error_count.columns = ['Time', 'machineID', 'error1', 'error2',
'error3', 'error4', 'error5']

反射(reflect)这一点。

提前谢谢

最佳答案

好吧,如果您观察的话,Time已经设置为索引。您可以通过查询df.index.name来验证这一点,它应该返回Time

对于第二个查询,您可以将 TimeID 设置为索引,然后调用 pd.get_dummies。请注意,此处假设 Time 已经是数据中的第一个索引列。我们将使用 set_index(...,append=True) 添加另一个。

# df = df.replace('None', np.nan) # optional step, if `None` is a string
df

ID Error1 Error2
Time
2010-01-01 00:00:31.690 105278.0 NaN 5
2010-01-01 00:00:32.000 105278.0 1 NaN
2010-01-01 00:00:32.140 105278.0 3 NaN
2010-01-01 00:00:32.350 105278.0 NaN 7
2010-01-01 00:00:32.460 105278.0 NaN 1

pd.get_dummies(
df.set_index('ID', append=True), prefix='', prefix_sep='')\
.add_prefix("Error")\
.reset_index()

Time ID Error1 Error3 Error1 Error5 Error7
0 2010-01-01 00:00:31.690 105278.0 0 0 0 1 0
1 2010-01-01 00:00:32.000 105278.0 1 0 0 0 0
2 2010-01-01 00:00:32.140 105278.0 0 1 0 0 0
3 2010-01-01 00:00:32.350 105278.0 0 0 0 0 1
4 2010-01-01 00:00:32.460 105278.0 0 0 1 0 0

关于python - Keyerror 多索引数据框 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48591768/

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