【问题标题】:calling function with pandas column as argument以 pandas 列作为参数调用函数
【发布时间】:2019-11-30 11:35:30
【问题描述】:

我写了一个函数,它接受一个 pandas 数据框和它的两列。在函数内部,我想将第一列的元素按第二列的元素分组。该函数的目标是使用 matplotlib 生成一个条形图,用于绘制分组计数。我不知道如何引用列参数,以便函数内部的 group-by 调用可以识别它们。

我尝试使用 df['col'] 和 'col' 但这些都不起作用。当我使用 df['col'] 时,我收到此错误:

AttributeError: 'DataFrameGroupBy' object has no attribute 'x'

当我使用“col”时,我得到了这个错误:

AttributeError: 'DataFrameGroupBy' object has no attribute 'x'

这里是一个示例实现,首先不使用函数,生成预期结果,然后使用函数。

import pandas as pd

# generate dataframe
df = pd.DataFrame()
df['col_A'] = [1, 4, 3, 2, 2, 1, 1, 4, 3, 2]
df['col_B'] = ['a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c']

# plot counts
import matplotlib.pyplot as plt

counts = df.groupby('col_B').col_A.count()
counts = counts.sort_values(ascending=False)

fig = plt.figure(figsize=(10,8))
counts.plot.barh(ylim=0).invert_yaxis()

# plot count with function
def count_barplot(data, x, y):

    counts = data.groupby(y).x.count()
    counts = counts.sort_values(ascending=False)

    fig = plt.figure(figsize=(10,8))
    counts.plot.barh(ylim=0).invert_yaxis()

# function call
count_barplot(df, df['col_A'], df['col_B'])

如何在函数内部和函数调用中指定数据框列参数,以便group-by函数识别?

【问题讨论】:

    标签: pandas function dataframe arguments


    【解决方案1】:

    这样对我有用:

    def count_barplot(data, x, y):
    
        counts = data.groupby(y)[x].count()
        counts = counts.sort_values(ascending=False)
    
        fig = plt.figure(figsize=(10,8))
        counts.plot.barh(ylim=0).invert_yaxis()
    
    # function call
    count_barplot(df, 'col_A', 'col_B')
    

    【讨论】:

      【解决方案2】:

      问题在于您的函数调用提供了一个数据框和两个系列作为其参数,而您要传递的是一个数据框和列名。请注意,您还希望使用[] 语法来引用groupby 中的列,并且可以使用内置的value_counts() 方法简化计数方法。

      因此,使用您的语法:

      # plot count with function
      def count_barplot(data, x, y):
      
          counts = data.groupby(y)[x].count()
          counts = counts.sort_values(ascending=False)
      
          fig = plt.figure(figsize=(10,8))
          counts.plot.barh(ylim=0).invert_yaxis()
      
      count_barplot(df, 'col_A', 'col_B')
      

      或更简单地说:

      # plot count with function
      def count_barplot(data, y):
      
          counts = df[y].value_counts()
      
          fig = plt.figure(figsize=(10,8))
          counts.plot.barh(ylim=0).invert_yaxis()
      
      # function call
      count_barplot(df, 'col_B')
      

      甚至

      def count_barplot(data, x, y):
          fig = plt.figure(figsize=(10,8))
          df[y].value_counts(ascending=True).plot.barh(ylim=0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-04
        • 2015-07-02
        相关资源
        最近更新 更多