How to update some of the rows from another series in pandas using df.update

ぐ巨炮叔叔 提交于 2019-12-11 19:26:22

问题


I have a df like,

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

converting to time delta

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

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]

now, updating df with odd_df,

as per the documentation it should give my expected output.

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

What I am getting,

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.


回答1:


Try this instead:

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

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.

In your code here:

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

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



来源:https://stackoverflow.com/questions/52569194/how-to-update-some-of-the-rows-from-another-series-in-pandas-using-df-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!