简体   繁体   中英

how to filter the values based on some condition PANDAS

I want to filter out and return a column based on whether each country has more F than M. For example, if a country has more F than M, the column would return True, otherwise False. How can I do this in pandas? please help. Thank you so much.

I've already filtered out the country codes and the Sex and how many there are. I just need to filter and return a TF value based on the count

 NOC  Sex
AFG  M        2
AHO  M        1
ALG  F        3
     M       14
ANZ  F        2
           ... 
WIF  M        5
YUG  F       60
     M      330
ZAM  M        2
ZIM  F       22

The output you expect is unclear, but you could do:

(df.pivot(columns='NOC', values='Sex')
   .fillna(0)
   .assign(more_F=lambda d: d['F'].gt(d['M']))
)

if your input is a Series with a MultiIndex:

(ser.unstack(level='Sex')
    .fillna(0)
    .assign(more_F=lambda d: d['F'].gt(d['M']))
)

output:

NOC     F      M  more_F
AFG   0.0    2.0   False
AHO   0.0    1.0   False
ALG   3.0   14.0   False
ANZ   2.0    0.0    True
WIF   0.0    5.0   False
YUG  60.0  330.0   False
ZAM   0.0    2.0   False
ZIM  22.0    0.0    True
import pandas as pd

# This is a sample dataframe.
# Make sure that you switch out the name of your dataframe in the code.
# This dataframe is called "df"
df=pd.DataFrame({"SEX":("M", "F", "M")})

# Define two counters
# One counts the occurence of "F"
f_counter=0
# One counts the occurence of "M"
m_counter=0

# Now iterate through each entry in the column "SEX"
for index in df.index:
    # Check if the entry is equal to "F"
    if df["SEX"][index] == "F":
        # If this is true, we will raise our F-counter by 1
        f_counter += 1
    else:
        # If this is not true, we will raise our M-counter by 1
        m_counter += 1

# Initialize our compare variable
compare=False
#Compare the F-counter with the M-counter
if f_counter > m_counter:
    # If we have more F than M, define counter as True
    compare=True
else:
    # If we have more M than F, define counter as False
    compare=False

# Print our result
print(compare)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM