![](/img/trans.png)
[英]how to replace values of an individual row and specific columns in pandas data frame
[英]Pandas: How to replace values in a Data Frame using other Data Frame's columns
我想使用另一個數據框作為映射的參考將數據框 A 中的值替換為“1”,如下所示:
原始數據幀 A:
Index 201901 201902 201903
a 0 0 0
b 0 0 0
c 0 0 0
d 0 0 0
參考數據幀 B
Index Month
a 201902
b 201901
結果數據幀 C
Index 201901 201902 201903
a 0 1 0
b 1 0 0
c 0 0 0
d 0 0 0
我試過 loc 但還沒有找到讓它工作的方法。 有什么建議?
您可以使用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
看起來沒有必要迭代。 我有一個使用pd.get_dummies
和pd.DataFrame.update
的簡單解決方案
dfA.update(pd.get_dummies(dfB.Month.apply(str)))
我使用了.apply(str)
因為 dfB 的內容注冊為整數,但 A 中的列是字符串,因此如果字段不匹配,則update
將不起作用
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 分配
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.