在Pandas中,由于其完善的索引方法,我可以轻松地以各种方式提取数据。但是,我仍然困惑如何更改现有DataFrame中的数据。
下面的代码中,我有两个数据框,并且我的目标是从第二个数据框中的值更新第一个数据框中特定行的值。我该如何实现?
import pandas as pd
df = pd.DataFrame({'filename' : ['test0.dat', 'test2.dat'],
'm': [12, 13], 'n' : [None, None]})
df2 = pd.DataFrame({'filename' : 'test2.dat', 'n':16}, index=[0])
# this overwrites the first row but we want to update the second
# df.update(df2)
# this does not update anything
df.loc[df.filename == 'test2.dat'].update(df2)
print(df)
提供
filename m n
0 test0.dat 12 None
1 test2.dat 13 None
[2 rows x 3 columns]
但是我该如何实现这个目标:
filename m n
0 test0.dat 12 None
1 test2.dat 13 16
[2 rows x 3 columns]