简体   繁体   English

Pandas:如何使用其他数据框的列替换数据框中的值

[英]Pandas: How to replace values in a Data Frame using other Data Frame's columns

I want to replace the values in a dataframe A with "1" using another data frame as reference to map it, something like this:我想使用另一个数据框作为映射的参考将数据框 A 中的值替换为“1”,如下所示:

Original Data Frame A:原始数据帧 A:

Index  201901    201902    201903
a      0         0         0
b      0         0         0
c      0         0         0
d      0         0         0

Reference Data Frame B参考数据帧 B

Index  Month
a      201902
b      201901

The result Data Frame C结果数据帧 C

Index  201901    201902    201903
a      0         1         0
b      1         0         0
c      0         0         0
d      0         0         0

I've tried with loc but haven't found a way to make it work.我试过 loc 但还没有找到让它工作的方法。 Any suggestions?有什么建议?

You can use df.iterrows() to iterate through the rows of the second dataframe and use df.at[] to set the values where you need to.您可以使用df.iterrows()遍历第二个数据帧的行,并使用df.at[]在需要的地方设置值。

df = pd.DataFrame([[0,0,0], [0,0,0], [0,0,0], [0,0,0]], columns=['201901', '201902', '201903'])
df.index=['a', 'b','c', 'd']
print(df)
#    201901  201902  201903
# a       0       0       0
# b       0       0       0
# c       0       0       0
# d       0       0       0

dfb = pd.DataFrame(['201902', '201901'], columns=['month'])
dfb.index = ['a', 'b']
print(dfb)
#     month
# a  201902
# b  201901

for i, row in dfb.iterrows():
    df.at[i, row] = 1

print(df)
#    201901  201902  201903
# a       0       1       0
# b       1       0       0
# c       0       0       0
# d       0       0       0

Looks like there's no need to iterate.看起来没有必要迭代。 I have a simple solution using pd.get_dummies and pd.DataFrame.update我有一个使用pd.get_dummiespd.DataFrame.update的简单解决方案

dfA.update(pd.get_dummies(dfB.Month.apply(str)))

I used the .apply(str) because the content of dfB registered as an integer but the columns from A are strings, so the update won't work if the fields don't match我使用了.apply(str)因为 dfB 的内容注册为整数,但 A 中的列是字符串,因此如果字段不匹配,则update将不起作用

Output:输出:

       201901  201902  201903
Index                        
a         0.0     1.0       0
b         1.0     0.0       0
c         0.0     0.0       0
d         0.0     0.0       0

Numpy assign Numpy 分配

df.values[df.index.get_indexer(dfb.index),df.columns.get_indexer(dfb.month)]=1
df
Out[1081]: 
   201901  201902  201903
a       0       1       0
b       1       0       0
c       0       0       0
d       0       0       0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM