I wanna do 2 similar operations with Pandas in Python 3. One with tilde and another without tilde.
1 - df = df[~(df.teste.isin(["Place"]))]
2 - df = df[(df.teste.isin(["Place"]))]
I tried to declare the tilde as variable, so I could write just one line and then decide if I wanna use with or without tilde. But it doesn't work:
tilde = ["~", ""]
df = df[tilde[0](df.teste.isin(["Place"]))]
Is possible do something that could reduce my code? Cause I am writing many equal lines just exchanging the tilde...
Thanks!
Why I wanna the tilde as variable:
def server_latam(df):
df.rename(columns={'Computer:OSI':'OSI'}, inplace=True)
df = df[~(df.teste.isin(["Place"]))]
df1 = df.loc[df.model != 'Virtual Platform', 'model'].count()
print("LATAM")
print("Physical Servers: ",df1)
df2 = df.loc[df.model == 'Virtual Platform', 'model'].count()
print("Virtual Servers: ",df2)
df3 = df.groupby('platformName').size().reset_index(name='by OS: ')
print(df3)
def server_latam_without_tilde(df):
df.rename(columns={'Computer:OSI':'OSI'}, inplace=True)
df = df[(df.teste.isin(["Place"]))]
df1 = df.loc[df.model != 'Virtual Platform', 'model'].count()
print("LATAM")
print("Physical Servers: ",df1)
df2 = df.loc[df.model == 'Virtual Platform', 'model'].count()
print("Virtual Servers: ",df2)
df3 = df.groupby('platformName').size().reset_index(name='by OS: ')
print(df3)
In the second line of each function the tilde appears.
You could possibly condense your code a little by defining your tests and then iterating over those. Let me illustrate:
That way, you only have two linesdoing the actual work, and simply adding another test to the list saves you duplicating code. No idea if this is what you want, though.
For your limited use case, there is limited benefit in what you are requesting.
GroupBy
Your real problem, however, is the number of variables you are having to create. You can halve them via
GroupBy
and a calculated grouper:Then access your dataframes via
dfs[0]
anddfs[1]
, sinceFalse == 0
andTrue == 1
. There is a benefit with this last example. You now remove the need to create new variables unnecessarily. Your dataframes are organized since they exist in the same dictionary.Function dispatching
Your precise requirement can be met via the
operator
module and an identity function:Sequence unpacking
If your intention is to use one line, use sequence unpacking:
Note you can replicate the
GroupBy
result via:But this is verbose and convoluted. Stick with the
GroupBy
solution.