我是 python 的新手,并试图用 Pandas 中的数据帧做一些工作
左侧是主数据帧 (df1) 的一部分,右侧是第二个 (df2)。目标是使用基于几个条件逻辑的字符串填充 df1['vd_type'] 列。我可以使用嵌套的 np.where() 函数来完成这项工作,但是随着它深入层次结构,运行时间太长了,所以我正在寻找一个更优雅的解决方案。
逻辑的英文版本是这样的:对于 df1['vd_type']:如果 df1['shape'] == df2['vd_combo'] 中的前两个字符 AND df1['vd_pct'] <= df2['combo_value '],然后在这两个条件都为真的行上返回 df2['vd_combo'] 中的最后 3 个字符。如果在 df2 中找不到两个条件都为真的行,则返回“vd4”。
提前致谢!
编辑#2:所以我想基于另一个变量实现第三个条件,其他一切都相同,除了在 df1 中还有另一列“log_vsc”具有现有值,目标是填写一个空的 df1 列“vsc_type” ' 与同一方案中的 4 个字符串之一。额外的条件只是我们刚刚定义的“vd_type”将与拆分“vsc_combo”产生的“vd”列匹配。
df3 = pd.DataFrame()
df3['vsc_combo'] = ['A1_vd1_vsc1','A1_vd1_vsc2','A1_vd1_vsc3','A1_vd2_vsc1','A1_vd2_vsc2' etc etc etc
df3['combo_value'] = [(number), (number), (number), (number), (number), etc etc
df3[['shape','vd','vsc']] = df3['vsc_combo'].str.split('_', expand = True)
def vsc_condition( row, df3):
df_select = df3[(df3['shape'] == row['shape']) & (df3['vd'] == row['vd_type']) & (row['log_vsc'] <= df3['combo_value'])]
if df_select.empty:
return 'vsc4'
else:
return df_select['vsc'].iloc[0]
## apply vsc_type
df1['vsc_type'] = df1.apply( vsc_condition, args = ([df3]), axis = 1)
这有效!!再次感谢!
所以你的输入是这样的:
import pandas as pd
df1 = pd.DataFrame({'shape': ['A2', 'A1', 'B1', 'B1', 'A2'],
'vd_pct': [0.78, 0.33, 0.48, 0.38, 0.59]} )
df2 = pd.DataFrame({'vd_combo': ['A1_vd1', 'A1_vd2', 'A1_vd3', 'A2_vd1', 'A2_vd2', 'A2_vd3', 'B1_vd1', 'B1_vd2', 'B1_vd3'],
'combo_value':[0.38, 0.56, 0.68, 0.42, 0.58, 0.71, 0.39, 0.57, 0.69]} )
如果您不反对在 df2 中创建列(如果有问题,您可以在最后删除它们),您可以生成两列shape
并vd
通过拆分列vd_combo
:
df2[['shape','vd']] = df2['vd_combo'].str.split('_',expand=True)
然后你可以创建一个condition
你将使用的函数,apply
例如:
def condition( row, df2):
# row will be a row of df1 in apply
# here you select only the rows of df2 with your conditions on shape and value
df_select = df2[(df2['shape'] == row['shape']) & (row['vd_pct'] <= df2['combo_value'])]
# if empty (your condition not met) then return vd4
if df_select.empty:
return 'vd4'
# if your condition met, then return the value of 'vd' the smallest
else:
return df_select['vd'].iloc[0]
现在你可以创建你的专栏vd_type
中df1
有:
df1['vd_type'] = df1.apply( condition, args =([df2]), axis=1)
df1
就好像:
shape vd_pct vd_type
0 A2 0.78 vd4
1 A1 0.33 vd1
2 B1 0.48 vd2
3 B1 0.38 vd1
4 A2 0.59 vd3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句