【发布时间】:2017-06-22 13:25:28
【问题描述】:
我正在对 pandas 数据框进行大量操作。例如查找列内的 max、min 和 average 以及 return the column names in a new column。现在我试图将这些东西包装到一个函数中,并在这个函数中使用max() 和/或min() 作为参数。
下面是一个 sn-p,它以非常简化的方式描述了我正在尝试做的事情。在其当前状态下,它还返回所需输出的描述。但 sn-p 不具备所需的功能和灵活性。
设置:
# Sample dataframe
df = pd.DataFrame({'col_A':[1,20,6,1,3]})
def findValue(function, df, colname):
print(function) # just a placeholder
df[colname] = df.max()[0]
return df
df2 = findValue(function='max', df=df, colname='col_B')
print(df)
输出 1:
col_A col_B
0 1 20
1 20 20
2 6 20
3 1 20
4 3 20
天真的尝试:
# Sample dataframe
df = pd.DataFrame({'col_A':[1,20,6,1,3]})
# The function I would like to use in another function is max()
# My function
def findValue(function, df, colname):
df[colname] = df.function()[0]
return df
df2 = findValue(function=max(), df=df , colname='col_B')
print(df)
输出 2:
Traceback (most recent call last):
File "<ipython-input-7-85964ff29e69>", line 1, in <module>
df2 = findValue(function=max(), df=df , colname='col_B')
TypeError: max expected 1 arguments, got 0
如何更改上面的 sn-p 以便可以将function = max() 更改为function = min() 或findValue() 的参数中的任何其他函数?或者甚至定义一个以类似方式使用的函数列表?
感谢您的任何建议!
【问题讨论】:
-
并不是这正是您正在寻找的,但是您知道
describe()方法吗?将返回 max、min、mean、std 的 DataFrame。 dev.,计算 DataFrame 中的每个 col(或这些值的 Series,如果在 Series 上运行)。 [文档] (pandas.pydata.org/pandas-docs/stable/generated/…) -
如果您查看问题中的链接,您会发现我将使用我正在寻找的东西作为更大功能的一部分,我不仅使用
describe()涵盖的措施。但它肯定会有用,所以谢谢你的提示!
标签: python-3.x function pandas