如何根据条件从一个数据框中替换一个数据框中的列值?

时间:2018-09-28 04:37:37

标签: python pandas

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar","Panda", "Panda", "Zootopia", "Zootopia"],"B":[0,1,1,1,0,1,1,1]})
df1 = pd.DataFrame({"A":["foo", "foo", "foo", "bar","Panda", "Panda", "Zootopia", "Zootopia","Toy Story"]})

如果df和df1中的列 A 相匹配,则将df1列A替换为df列 B 的值也计算未替换的值的数量,并列出它们的列表。 / p>

预期产量

    A
0   0.0
1   1.0
2   1.0
3   1.0
4   0.0
5   1.0
6   1.0
7   1.0
8   Toy Story

未替换计数:1

未替换的数据框:

 0  A
     Toy Story

1 个答案:

答案 0 :(得分:1)

这是一种解决方案:

num = len(df['A'])
if all(df1['A'][:num]==df['A'][:num]):
    df1['A'][:num] = df['B']

df1的输出:

           A
0          0
1          1
2          1
3          1
4          0
5          1
6          1
7          1
8  Toy Story

如果您不想更改df1,则可以对其进行复制并运行代码:

num = len(df['A'])
df1_copy = df1.copy()
if all(df1_copy['A'][:num]==df['A'][:num]):
    df1_copy['A'][:num] = df['B']

df1的输出:

           A
0        foo
1        foo
2        foo
3        bar
4      Panda
5      Panda
6   Zootopia
7   Zootopia
8  Toy Story

df1_copy的输出:

           A
0          0
1          1
2          1
3          1
4          0
5          1
6          1
7          1
8  Toy Story