python - 使用 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
这可以通过一个步骤还是几个有效的步骤来实现?
解决方案
您正在寻找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
推荐阅读
- css - 浏览器找不到 CSS 图像路径
- runtime-error - Unable to Run Test Runner Using TestNg getting cucumber.runtime.CucumberException: cucumber.runtime.CucumberException: There are undefined steps
- r - 我应该如何进行网络抓取该网站上的所有位置:'https://shoppers.instacart.com/instacart-jobs'
- c++ - 在使用 OpenGL 上下文时调用 SDL_GL_SwapWindow 时如何避免高 GPU 使用率?
- pipeline - Deepstream 将来自 Minio 的批量图像作为输入
- javascript - 获取不同域 iframe 内容的大小
- c - 如何使用 void 指针通过多个级别将多个结构作为同一参数传递
- java - 编写一个名为 isPrime 的方法,它接受一个整数作为参数,如果参数是素数则返回 true
- ios - Swift:nskeyedunachiver 失败并以 'NSInvalidArgumentException' 终止应用程序,原因:'-[__NSCFData count]
- kotlin - 如何在 kotlin 中使用另一个列表过滤和排序列表