对熊猫数据框的操作

时间:2020-04-01 07:46:06

标签: python pandas

我不知道如何用语言来描述我的问题,我只是对其进行建模

问题建模:

假设我们有两个具有相同列的数据框df1,df2

df1

idx | col1 | col2 | col3 |  col4 
---------------------------------
 0  |  1   | -100 |   2  |  -100 

df2

idx | col1 | col2 | col3 |  col4
---------------------------------
 0  |  12  |  23  |  34  |   45 

鉴于我们得到的这两个df-s

df_result

idx | col1 | col2 | col3 |  col4 
---------------------------------
 0  |  1   |  23  |   2  |   45 

即我们得到df1,其中所有-100分别替换为df2中的值。

问题:我该如何无for循环?尤其是在大熊猫中或在两个相同大小的清单上是否有一项操作可以满足我们的需要?

PS:我可以用for循环来做,但是会慢很多。

1 个答案:

答案 0 :(得分:2)

您可以使用此:

df1[df1==-100] = df2

这是它的逐步操作方式:

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.array([[1,-100,2,-100],[-100,3,-100,-100]]), columns=['col1','col2','col3','col4'])
df1

col1    col2    col3    col4
1       -100    2       -100
-100    3       -100    -100


df2 = pd.DataFrame(np.array([[12,23,34,45],[1,2,3,4]]), columns=['col1','col2','col3','col4'])
df2

col1    col2    col3    col4
12      23      34      45
1       2       3       4

通过使用布尔索引,您可以做到

df1==-100

col1    col2    col3    col4
False   True    False   True
True    False   True    True

因此,当True时,您可以分配df2的相应值:

df1[df1==-100]=df2
df1

col1    col2    col3    col4
1       23      2       45
1       3       3       4