如何使用df.update更新 pandas 中另一个系列的某些行 [英] How to update some of the rows from another series in pandas using df.update

查看:250
本文介绍了如何使用df.update更新 pandas 中另一个系列的某些行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有df之类的

    stamp   value
0   00:00:00    2
1   00:00:00    3
2   01:00:00    5

转换时间Delta

df['stamp']=pd.to_timedelta(df['stamp'])

仅切片奇数索引并加30分钟,

slicing only odd index and adding 30 mins,

odd_df=pd.to_timedelta(df[1::2]['stamp'])+pd.to_timedelta('30 min')
#print(odd_df)
1  00:30:00
Name: stamp, dtype: timedelta64[ns]

现在,更新df按照

now, updating df with odd_df,

。 html rel = nofollow noreferrer>文档,它应该给出我的预期输出。

as per the documentation it should give my expected output.

预期输出:

df.update(odd_df)
#print(df)
    stamp   value
0   00:00:00    2
1   00:30:00    3
2   01:00:00    5

我得到的是

df.update(odd_df)
#print(df)

    stamp   value
0   00:30:00    00:30:00
1   00:30:00    00:30:00
2   00:30:00    00:30:00

请帮助,这有什么问题。

please help, what is wrong in this.

推荐答案

尝试以下方法:

df.loc[1::2, 'stamp'] += pd.to_timedelta('30 min')

这可确保您仅更新值在.loc()函数指定的DataFrame中,同时保留其余原始DataFrame。要测试,请运行df.shape。您将使用上述方法获得(3,2)。

This ensures you update just the values in DataFrame specified by the .loc() function while keeping the rest of your original DataFrame. To test, run df.shape. You will get (3,2) with the method above.

在此处的代码中:

odd_df=pd.to_timedelta(df[1::2]['stamp'])+pd.to_timedelta('30 min')

odd_df数据框仅包含原始数据框的一部分。您切片的部分。奇数df的形状为(1,)。

The odd_df DataFrame only has parts of your original DataFrame. The parts you sliced. The shape of odd_df is (1,).

这篇关于如何使用df.update更新 pandas 中另一个系列的某些行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆