![](/img/trans.png)
[英]How to create new column based on substrings in other column in a pandas dataframe?
[英]Pandas dataframe, how to create a new totals column containing values based on other column
>>> df
Dr Name Type Total Fund Total
0 Debtors Balance Sheet 200.00 0.00
1 Bank Balance Sheet 352.25 100.00
4 General Fund Fund -100.00 -252.25
5 Building Fund Fund 0.00 -300.00
我想要創建一個新列,填充Totals or
基金總計。
如果Type
是Balance Sheet
,我希望使用Total
列 - 如果Type
是Fund
,則使用Fund Total
。 要產生這個:
>>> df
Dr Name Type Total Fund Total Grand Total
0 Debtors Balance Sheet 200.00 0.00 200.00
1 Bank Balance Sheet 352.25 100.00 352.25
4 General Fund Fund -100.00 -252.25 -252.25
5 Building Fund Fund 0.00 -300.00 -300.00
謝謝
這是一個可能的解決方案:
df["Grand Total"] = df.where(df["Type"] == "Fund")["Fund Total"].fillna(df["Total"])
使用df.where
我僅在類型為 Fund 的情況下提取列Fund Total
(其他行將是nan
。然后fillna
使用另一列填充那些nan
(在這種情況下為Total
)
另一種方法是使用where
from numpy
:
import panda as pd
df['Grand Total'] = np.where(df['Type'] == 'Fund', df['Fund Total'], df['Total'])
print(df)
# Output
Dr Name Type Total Fund Total Grand Total
0 Debtors Balance Sheet 200.00 0.00 200.00
1 Bank Balance Sheet 352.25 100.00 352.25
4 General Fund Fund -100.00 -252.25 -252.25
5 Building Fund Fund 0.00 -300.00 -300.00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.