[英]Adding a new column based on values of another column in Pandas(python)
[英]Python Pandas adding column values based on condition
我有一個DataFrame(df),其中包含以下值:
Title
fintech_countries
US 60
UK 54
India 28
Australia 25
Germany 13
Singapore 11
Canada 10
我想添加值<25的所有國家/地區,並將其顯示為“其他”及其總和(34)。
我已通過以下代碼為國家/地區創建了列名:
df1 = df.rename_axis('fintech_countries').rename_axis("countries", axis="columns" , inplace=True)
countries Title
fintech_countries
US 60
UK 54
India 28
Australia 25
Germany 13
Singapore 11
Canada 10
現在,我根據StackOverflow上的另一個查詢嘗試了以下代碼:
df1.loc[df1['Title'] < 25, "countries"].sum()
但是我收到以下錯誤:
KeyError: 'the label [countries] is not in the [columns]'
有人可以幫忙嗎? 我需要最終輸出為:
countries Title
fintech_countries
US 60
UK 54
India 28
Australia 25
Others 34
TIA
使用loc
設置擴展和boolean indexing
過濾的解決方案:
mask = df['Title'] < 25
print (mask)
fintech_countries
US False
UK False
India False
Australia False
Germany True
Singapore True
Canada True
Name: Title, dtype: bool
df1 = df[~mask].copy()
df1.loc['Others', 'Title'] = df.loc[mask, 'Title'].sum()
df1.Title = df1.Title.astype(int)
print (df1)
countries Title
fintech_countries
US 60
UK 54
India 28
Australia 25
Others 34
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.