努力掌握更新/合并/连接等,以实现我认为简单的合并或更新过程。我有 df(记录值)和 df2(带 0 的时间序列),并想用 df 的相应记录值更新/替换 df2 中的值,匹配 date_time。
例子:df=
Date_Time Perc
03/03/2010 00:05 1.0
03/03/2010 00:15 2.0
df2 =
Date_Time Perc
03/03/2010 00:00 0.0
03/03/2010 00:05 0.0
03/03/2010 00:10 0.0
03/03/2010 00:15 0.0
03/03/2010 00:20 0.0
返回结果的位置:
Date_Time Perc
03/03/2010 00:00 0.0
03/03/2010 00:05 1.0
03/03/2010 00:10 0.0
03/03/2010 00:15 2.0
03/03/2010 00:20 0.0
我发现这令人沮丧,因为在 http://pandas.pydata.org/pandas-docs/stable/merging.html 上有很好的信息和示例和一个关于 How to update values in a specific row in a Python Pandas DataFrame? 的多个解决方案的伟大 SO 问题但是尝试了几种方法,都没有用。
到目前为止已尝试:重新索引到 Date_time 和 df2.update(df) 变体、多个合并/连接/concat 变体、带有应用的改编定义(如下)...现在想知道我是否需要使用 iterrows (见下文?)。 任何关于正确方向的建议都将不胜感激……也许我在我的方法中遗漏了一些基本的东西……
def update_vals(row, data=data):
if row.Date_Time == df.Date_Time:
row.Perc = df.Perc
return row
for index, row in df2['Date_Time'].iterrows():
x = df2['Date_Time']
for index, row in df['Date_Time'].iterrows():
x2 = df['Date_Time']
if x2 ==x:
df2['Perc'] = df['Perc']
原以为这也行,但结果是(ValueError:无法从重复轴重新索引)
df.set_index('Date_Time', inplace=True)
df2.set_index('Date_Time', inplace=True)
df2.update(df[['Perc']])
请您参考如下方法:
df2
Perc
Date_Time
03/03/2010 00:00 0
03/03/2010 00:05 0
03/03/2010 00:10 0
03/03/2010 00:15 0
03/03/2010 00:20 0
df
Perc
Date_Time
03/03/2010 00:05 1
03/03/2010 00:15 2
df2.update(df)
Perc
Date_Time
03/03/2010 00:00 0
03/03/2010 00:05 1
03/03/2010 00:10 0
03/03/2010 00:15 2
03/03/2010 00:20 0
