2 回答

TA貢獻1784條經(jīng)驗 獲得超8個贊
編輯: Lambda 的回答給了我一個想法,讓我知道如何對要將此邏輯模式應(yīng)用于的許多列執(zhí)行此操作:
import pandas as pd
df1 = pd.DataFrame(dict(
InfoType = [None, None, None, None],
IncidentType = 'A C B B'.split(),
DangerType = [None, None, 'C', None],
))
df2 = pd.DataFrame(dict(
ParamCode = 'IncidentType IncidentType IncidentType DangerType'.split(),
ParamValue = 'A B C C'.split(),
ParmDesc1 = 'ABC GHI MNO STU'.split(),
))
for col in df1.columns[1:]:
dict_map = dict(
df2[df2.ParamCode == col][['ParamValue','ParmDesc1']].to_records(index=False)
)
df1[col] = df1[col].replace(dict_map)
print(df1)
這假設(shè) in 第一列之后的每一列df1都是需要更新的列,并且要更新的列名作為 的'ParamCode'列中的值存在df2。
Python 導(dǎo)師鏈接到代碼
這個問題可以使用一些自定義函數(shù)和pandas.Series.apply()來解決:
import pandas as pd
def find_incident_type(x):
if pd.isna(x):
return x
return df2[
(df2['ParamCode'] == 'IncidentType') & (df2['ParamValue']==x)
]["ParmDesc1"].values[0]
def find_danger_type(x):
if pd.isna(x):
return x
return df2[
(df2['ParamCode'] == 'DangerType') & (df2['ParamValue']==x)
]["ParmDesc1"].values[0]
df1 = pd.DataFrame(dict(
InfoType = [None, None, None, None],
IncidentType = 'A C B B'.split(),
DangerType = [None, None, 'C', None],
))
df2 = pd.DataFrame(dict(
ParamCode = 'IncidentType IncidentType IncidentType DangerType'.split(),
ParamValue = 'A B C C'.split(),
ParmDesc1 = 'ABC GHI MNO STU'.split(),
))
df1['IncidentType'] = df1['IncidentType'].apply(find_incident_type)
df1['DangerType'] = df1['DangerType'].apply(find_danger_type)
print(df1)
單步執(zhí)行python教程中的代碼
很有可能有更有效的方法來做到這一點。希望有知道的人分享一下。
df2此外,來自外部作用域的 ref被硬編碼到自定義函數(shù)中,因此僅適用于外部作用域中的變量名。如果您不希望這些函數(shù)依賴于該引用,則需要為pandas.Series.apply'參數(shù)使用參數(shù)。args

TA貢獻1851條經(jīng)驗 獲得超4個贊
使用查找表制作一個dict,然后替換原始數(shù)據(jù)框的列值。假設(shè)原始數(shù)據(jù)框是df1并且查找表是df2
...
dict_map = dict(zip(df2.ParamCode + "-" + df2.ParamValue, df2.ParmDesc1))
df1['IncidentType'] = ("IncidentType" +'-'+ df1.IncidentType).replace(dict_map)
df1['DangerType'] = ("DangerType" +'-'+ df1.DangerType).replace(dict_map)
...
添加回答
舉報