[英]How to get values from a Column in pandas if another column in same dataframe matches a condition?
Tax_Amount Rate SGST CGST IGST TDS Tax_Term
0 5697.0 9.0 NaN NaN NaN NaN CGST
1 954.0 9.0 NaN NaN NaN NaN TDS
2 1305.0 9.0 NaN NaN NaN NaN CGST
3 2724.0 9.0 NaN NaN NaN NaN SGST
4 18000.0 9.0 NaN NaN NaN NaN IGST
i Have a Dataframe as above, I want to have the Tax_Amount in all respective column if it matches the Colum Tax_Term.我有一个 Dataframe 如上所述,如果它与 Colum Tax_Term 匹配,我想在所有相应的列中都有 Tax_Amount。 Expected Output:-
预计 Output:-
Tax_Amount Rate SGST CGST IGST TDS Tax_Term
0 5697.0 9.0 NaN 5697.0 NaN NaN CGST
1 954.0 9.0 NaN 954.0 NaN 954.0 TDS
2 1305.0 9.0 NaN 1305.0 NaN NaN CGST
3 2724.0 9.0 2724.0 NaN NaN NaN SGST
4 18000.0 9.0 NaN NaN 18000.0 NaN IGST
I tried doing the same with below code however i didn't get the desired result.我尝试用下面的代码做同样的事情,但是我没有得到想要的结果。
final_df['SGST'] = final_df.query('Tax_Term == SGST')['Tax_Amount']
final_df['CGST'] = final_df.query('Tax_Term == CGST')['Tax_Amount']
final_df['IGST'] = final_df.query('Tax_Term == IGST')['Tax_Amount']
final_df['TDS'] = final_df.query('Tax_Term == TDS')['Tax_Amount']
any help will be appretiated.任何帮助将不胜感激。 Thanks.
谢谢。
You can use the apply method to achieve this.您可以使用 apply 方法来实现这一点。 The apply method allows you to apply a function to each row or column of a DataFrame.
apply 方法允许您将 function 应用于 DataFrame 的每一行或每一列。
Here is an example of how you can use the apply method to accomplish your task:以下是如何使用 apply 方法完成任务的示例:
def fill_tax_amount(row):
if row['Tax_Term'] == 'SGST':
row['SGST'] = row['Tax_Amount']
elif row['Tax_Term'] == 'CGST':
row['CGST'] = row['Tax_Amount']
elif row['Tax_Term'] == 'IGST':
row['IGST'] = row['Tax_Amount']
elif row['Tax_Term'] == 'TDS':
row['TDS'] = row['Tax_Amount']
return row
final_df = final_df.apply(fill_tax_amount, axis=1)
This will apply the fill_tax_amount function to each row in the final_df DataFrame, and the function will fill the appropriate tax amount based on the value in the Tax_Term column.这会将 fill_tax_amount function 应用于 final_df DataFrame 中的每一行,function 将根据 Tax_Term 列中的值填充适当的税额。 The axis=1 argument specifies that the function should be applied to each row rather than each column.
axis=1 参数指定 function 应应用于每一行而不是每一列。
Alternatively, you can use the pivot_table method to achieve the same result:或者,您可以使用 pivot_table 方法来获得相同的结果:
final_df = final_df.pivot_table(index=['Rate', 'TDS', 'Tax_Term'],
columns='Tax_Term',
values='Tax_Amount',
aggfunc='first').reset_index()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.