[英]Compare Dataframes of different size and create a new one if condition is met
I need help to figure out the following problem:我需要帮助来解决以下问题:
I have two(2) dataframes of different sizes.我有两 (2) 个不同大小的数据框。 I need to compare the values and, if the condition is met, replace the values in Dataframe 1.
我需要比较这些值,如果满足条件,请替换 Dataframe 1 中的值。
If the values for a Material and Char in Dataframe 1 are = "Y", I need to get the "Required or Optional" value from Dataframe 2. If it's Required, then I replace the "Y" with "Y_REQD" otherwise if it's Optional then replace "Y" with "Y_OPT".如果 Dataframe 1 中的 Material 和 Char 的值为 =“Y”,我需要从 Dataframe 2 中获取“必需或可选”值。如果是必需的,那么我将“Y”替换为“Y_REQD”,否则如果是可选然后将“Y”替换为“Y_OPT”。
I've been using For loops but now the code is getting too complicated which hints me this may not be the best way.我一直在使用 For 循环,但现在代码变得太复杂了,这暗示我这可能不是最好的方法。
Thanks in advance.提前致谢。
This is more like a pivot
problem, then we can reindex
the dataframe then sum这更像是一个
pivot
问题,然后我们可以reindex
dataframe 然后求和
df1=df1.replace({'Y':'Y_'})+df2.pivot(*df2.columns).reindex_like(df1).fillna('')
Mostly agree with @WeNYoBen's answer.大多同意@WeNYoBen 的回答。 But to make it completely right, dataframe2 need to be revised using df.replace.
但要使其完全正确,需要使用 df.replace 修改 dataframe2。
Short version:精简版:
df1=df1.replace({'Y':'Y_'})+df2.replace({'Rqd': 'REQD', 'Opt': 'OPT'}).pivot(*df2.columns).reindex_like(df1).fillna('')
Long version:长版:
# break short into steps
# 1. replace
df2 = df2.replace({'Rqd': 'REQD', 'Opt': 'OPT'})
# 2. pivot
df2 = df2.pivot(*df2.columns)
# 3. reindex
df2 = df2.reindex_like(df1)
# 4. fillna(cleanup df with string form)
df2 = df2.fillna('')
# 5. map on df1 and add up with df2
df1=df1.replace({'Y':'Y_'})+df2
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.