python - 将修改后的子框架嵌入到原始子框架中

标签 python pandas bigdata

我有 2 个 pandas 数据框,其中一个包含第一个数据框的修改后的选定行(它们具有相似的列)。 为了简单起见,下面的框架说明了这个问题。

df1 =                 df2 =
      A B C                  A B C
0     1 2 3           1      20 30 40
1     2 3 4           3      40 50 60
2     3 4 5
3     4 5 6

是否有比下面的代码更有效和Pythonic的方法,通过覆盖值将df2嵌入到df1中? (使用高维框架)

for index, row in df2.iterrows():
    df1.ix[index,:] = df2.ix[index, :]

结果是:

df1 =
     A  B  C
0    1  2  3
1    20 30 40
2    3  4  5
3    40 50 60

最佳答案

您可以使用update要使用另一个 df 更新一个 df,其中行和列标签同意更新值,您需要使用 astype 转换为 int,因为 dtype 已更改为 float由于缺失值:

In [21]:
df1.update(df2)
df1 = df1.astype(int)
df1

Out[21]:
    A   B   C
0   1   2   3
1  20  30  40
2   3   4   5
3  40  50  60

关于python - 将修改后的子框架嵌入到原始子框架中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40378126/

相关文章:

python - Pygame 朝某个方向移动图像

python - 在 Python 中保留除一列之外的重复行

python - 在python中读取大数据

python - 关于带有 n 排列的 Minhash 实现的建议

hadoop - 关于动态分区表插入而不在Hive中创建临时/临时表的问题

python - 在 Python3 中对具有 None 值的元组列表进行排序

python - python 中未调用 json 自定义 object_hook

python - 在 Pandas Dataframe 的几列上填写 na

python - bool 索引的优雅方法,列表中具有可变/动态数量的值

Python字符串转换,去掉空格,加连字符