相关疑难解决方法(0)

如何更新Python Pandas DataFrame中特定行的值?

使用Pandas中的漂亮索引方法,我可以通过各种方式提取数据.另一方面,我仍然对如何更改现有DataFrame中的数据感到困惑.

在下面的代码中,我有两个DataFrame,我的目标是从第二个df的值更新第一个df中特定行的值.我怎样才能做到这一点?

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)
Run Code Online (Sandbox Code Playgroud)

   filename   m     n
0  test0.dat  12  None
1  test2.dat  13  None

[2 rows x 3 columns]
Run Code Online (Sandbox Code Playgroud)

但我怎样才能做到这一点:

    filename   m     n
0  test0.dat  12  None
1  test2.dat  13  16 …
Run Code Online (Sandbox Code Playgroud)

python pandas

31
推荐指数
3
解决办法
8万
查看次数

标签 统计

pandas ×1

python ×1