我有一個 pandas 資料框 (df1),其中有一列包含一些“NaN”值,我想用另一個資料框 (df2) 中的值替換這些值。
這是必須映射的具有 NaN 的資料幀 (df1) 的一部分:
reporting_date_id filing_date_id
19910930 NaN
19920930 NaN
這是我想用來映射的資料框(df2),這有點棘手,因為它們具有相同的列名
reporting_date_id filing_date_id
19910930 19911118
19920930 19921116
19930930 19931122
我試圖以這種方式做到這一點,但它似乎不起作用
for n in range(len(df1)):
if df1['filing_date_id'].isna().loc[n]==True:
fix_date=df2[df2['reporting_date_id']==df1['reporting_date_id'].loc[n]]['filing_date_id']
df1['filing_date_id'].loc[n]=fix_date
uj5u.com熱心網友回復:
您可以通過reporting_date_id
另一個映射列,然后將其用于替換中的缺失值:DataFrame
Series.map
Series.fillna
s = df2.set_index('reporting_date_id')['filing_date_id']
df1['filing_date_id'] = df1['filing_date_id'].fillna(df1['reporting_date_id'].map(s))
uj5u.com熱心網友回復:
按索引對齊并使用fillna
. 然后再次重置索引。
idx = 'reporting_date_id'
result = df1.set_index(idx).fillna(df2.set_index(idx)).reset_index()
演示:
>>> df1
reporting_date_id filing_date_id
0 19910930 NaN
1 19920930 NaN
>>> df2
reporting_date_id filing_date_id
0 19910930 19911118
1 19920930 19921116
2 19930930 19931122
>>> idx = 'reporting_date_id'
>>> result = df1.set_index(idx).fillna(df2.set_index(idx)).reset_index()
>>> result
reporting_date_id filing_date_id
0 19910930 19911118.0
1 19920930 19921116.0
uj5u.com熱心網友回復:
我個人更喜歡@jezrael 的答案,但如果您有興趣在資料幀行上使用 for 回圈,您可以使用下面的代碼:
df1.set_index("reporting_date_id", inplace=True)
df2.set_index("reporting_date_id", inplace=True)
for index, row in df1.iterrows():
if row["filing_date_id"] != row["filing_date_id"] or row["filing_date_id"] == None:
df1.loc[index , "filing_date_id"] = df2.loc[index]["filing_date_id"]
df1
輸出
報告日期ID | 歸檔日期ID |
---|---|
19910930 | 19911118 |
19920930 | 19911118 |
uj5u.com熱心網友回復:
import pandas as pd
df1 = pd.DataFrame(
{
"reporting_date_id": [19910930, 19920930],
"filing_date_id": [None, None],
}
)
# repdateid filing_date_id
# 0 19910930 None
# 1 19920930 None
df2 = pd.DataFrame(
{
"reporting_date_id": [19910930, 19920930, 19930930],
"filing_date_id": [19911118, 19921116, 19931122],
}
)
# repdateid filing_date_id
# 0 19910930 19911118
# 1 19920930 19921116
# 2 19930930 19931122
result = pd.merge(df1, df2, on=["reporting_date_id", "reporting_date_id"])
result.drop(['filing_date_id_x'], axis=1)
這將保留兩個列,以防兩個列的相同reporting_date_id 具有不同的值。如果不是,您可以像上面那樣洗掉 NaN 列。
輸出:
repdateid filing_date_id_x filing_date_id_y
0 19910930 None 19911118
1 19920930 None 19921116
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/433030.html
上一篇:如何根據條件洗掉行
下一篇:負for回圈中的變數賦值