首页 > 解决方案 > 使用 Python Pandas 同时更改多个行和列值

问题描述

我想更改 10x10 熊猫数据框的 9 个成员的值,最好同时更改。我有一个 3x3 的值矩阵,比方说:

>>> import numpy as np
>>> import pandas as pd

>>> xx = np.array(range(1, 10)).reshape(3, 3)
>>> xx
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

现在我有一个 10x10 零数据框 df:

>>> df = pd.DataFrame(np.zeros(100).reshape(10, 10), index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], columns = ['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y'])
>>> df
     p    q    r    s    t    u    v    w    x    y
a  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
b  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
c  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
d  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
e  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
f  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
g  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
h  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
i  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
j  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0

我想在“b”、“d”和“g”行以及“t”、“v”和“w”列中插入 3x3 矩阵 xx,它们相交,这样之后它看起来像这样:

     p    q    r    s    t    u    v    w    x    y
a  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
b  0.0  0.0  0.0  0.0  1.0  0.0  2.0  3.0  0.0  0.0
c  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
d  0.0  0.0  0.0  0.0  4.0  0.0  5.0  6.0  0.0  0.0
e  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
f  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
g  0.0  0.0  0.0  0.0  7.0  0.0  8.0  9.0  0.0  0.0
h  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
i  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
j  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0

这可以通过一个步骤还是几个有效的步骤来实现?

标签: pythonpandasnumpy

解决方案


您正在寻找update方法:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.zeros(100).reshape(10, 10), 
                  index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 
                  columns = ['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y'])

xx = np.array(range(1, 10)).reshape(3, 3)
xx = pd.DataFrame(xx, index=['b', 'd', 'g'], columns=['t','v','w'])

df.update(xx)
df

输出:

      p   q   r   s   t   u   v   w   x   y
a   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
b   0.0 0.0 0.0 0.0 1.0 0.0 2.0 3.0 0.0 0.0
c   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
d   0.0 0.0 0.0 0.0 4.0 0.0 5.0 6.0 0.0 0.0
e   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
f   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
g   0.0 0.0 0.0 0.0 7.0 0.0 8.0 9.0 0.0 0.0
h   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
i   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
j   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0

文档解释得更详细:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html


推荐阅读