是不是可能将多个值输入到Python函数的单个变量中?

huangapple go评论70阅读模式
英文:

Is it possible to input multiple values into a single variable in a Python function?

问题

这是我的函数:

def function_drop_columns(x, y):
    return x.loc[:, ~(x.columns.str.endswith(y))]

x 始终只是一个输入,指定一个数据框。但是对于 y,可能有许多列我想要删除(它们以不同的字符串结尾)。是否有办法重写这个函数,使得 y 可以接受多个值作为输入?

我在想是否可以使用一些“或”操作符,但似乎没有起作用。

df1 = function_drop_columns(df, 'DATE' or 'STATE')

我需要更改函数本身,还是有办法重写输入以涵盖不同的值?

英文:

Here's my function:

def function_drop_columns (x,y): 
    return (x).loc[:,~(x).columns.str.endswith(y)]

x will always just be one input- specifying a dataframe. For y, however, there could be many columns I want to drop (which end with different strings). Is there any way to re-write this so y can be input with multiple values?

I was wondering if I could input some kind 'or' operator but it doesn't seem to have worked.

df1 = function_drop_columns (df,'DATE' or 'STATE')

Do I need to change the function itself or is there way to re-write the input to cover different values?

答案1

得分: 3

pandas.Series.str.endswith 允许将字符串元组用作模式。您可以使用:

function_drop_columns(df, ('DATE', 'STATE'))
英文:

pandas.Series.str.endswith allows tuple of strings as pattern. Use could use:

function_drop_columns(df, ('DATE', 'STATE'))

答案2

得分: 0

你可以在函数参数前使用 * 将值打包到你的函数中,比如 def function_drop_columns(x, *args):,它会将 x 后面的所有值打包起来:

def function_drop_columns(x, *y):
    print(x)
    print(y)

然后在控制台中输入以下代码:

>>> function_drop_columns("第一个值", "第二个值", "第三个值")

你会得到以下输出:

第一个值
('第二个值', '第三个值')

你也可以使用 ** 来传递带有关键字的值:

def function_drop_columns(x, **y):
    print(x)
    print(y)

然后在控制台中输入以下代码:

>>> function_drop_columns("第一个值", second="第二个值", third="第三个值")

你会得到以下输出:

第一个值
{'second': '第二个值', 'third': '第三个值'}
英文:

You can use * before an argument to pack value in your function like def function_drop_columns(x, *args): which pack all value after x like and :

def function_drop_columns(x, *y):
    print(x)
    print(y)

And with that you get in the console :

>>> function_drop_columns("First value", "Second value", "Third value")

First value
('Second value', 'Third value')

You can also use ** if your want to pass value with keyword like :

def function_drop_columns(x, **y):
    print(x)
    print(y)

And we get :

>>> function_drop_columns("First value", second="Second value", third="Third value")

First value
{'second': 'Second value', 'third': 'Third value'}

huangapple
  • 本文由 发表于 2023年4月6日 20:42:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75949664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定