【问题标题】:Python: Running function to append values to an empty list returns no valuesPython:运行函数将值附加到空列表不返回值
【发布时间】:2018-04-30 23:46:56
【问题描述】:

这可能是一个非常基本的问题,但我无法弄清楚。

我目前正在使用以下方法将值附加到空列表

shoes = {'groups':['running','walking']}
df_shoes_group_names = pd.DataFrame(shoes)

shoes_group_name=[]

for type in df_shoes_group_names['groups']:
    shoes_group_name.append(type)

shoes_group_name
['running', 'walking']

我正在尝试使用 for 循环来完成相同的操作,但是,当我执行循环时,列表​​返回为空白

shoes_group_name=[]

def list_builder(dataframe_name):
    if 'shoes' in dataframe_name:
        for type in df_shoes_group_names['groups']:
            shoes_group_name.append(type)

list_builder(df_shoes_group_names)

shoes_group_name
[]

函数的原因是最终我将拥有多个具有不同产品的 DF,所以我希望函数中只有 if 语句来处理每个列表的创建

例如,未来的示例可能如下所示:

df_shoes_group_names
df_boots_group_names
df_sandals_group_names

shoes_group_name=[]
boots_group_name=[]
sandals_group_name=[]


def list_builder(dataframe_name):
    if 'shoes' in dataframe_name:
        for type in df_shoes_group_names['groups']:
            shoes_group_name.append(type)
    elif 'boots' in dataframe_name:
        for type in df_boots_group_names['groups']:
            boots_group_name.append(type)
    elif 'sandals' in dataframe_name:
        for type in df_sandals_group_names['groups']:
            sandals_group_name.append(type)    

list_builder(df_shoes_group_names)
list_builder(df_boots_group_names)
list_builder(df_sandals_group_names)

不确定我是否以正确的方式处理此问题,因此不胜感激。

最好的,

【问题讨论】:

  • 嗯,这实际上应该有效,因为您在函数中传递了一个非原始 python 类型作为引用。也许“组”键中没有任何值?
  • 语句 if 'shoes' in x 在您的代码中评估 False。 'shoes' 是变量的名称,而不是字典键之一的名称。调用函数pd.DataFrames[shoes] 不会导致传递字符串shoes,而是传递一个恰好名为“shoes”的字典对象。
  • 您在shoes 中也没有任何名为'group' 的内容。您确实有一个名为'groups' 的东西,但这不是同一个键。或者,更确切地说,你会,但pd.DataFramesNameError;你可能是说pd.DataFrame
  • 对上面的组和数据框拼写错误进行了编辑。 if 语句用于搜索数据帧的名称是否包含鞋子、靴子或凉鞋,如果确实包含其中任何一个,它将将该数据帧中的值附加到空列表中。在我的示例中,关于靴子和凉鞋的数据框是空的;我列出了这些作为我将如何使用代码的示例
  • 您有一个名为function 的函数,它接受一个名为x 的参数!这种命名毫无意义。而且该函数正在修改全局范围内的列表,这使得理解它应该做什么变得更加不可能。

标签: python pandas loops for-loop


【解决方案1】:

您应该永远不要调用或搜索变量名,就像它是一个字符串一样。

相反,使用字典来存储可变数量的变量。

不好的做法

# dataframes
df_shoes_group_names = pd.DataFrame(...)
df_boots_group_names = pd.DataFrame(...)
df_sandals_group_names = pd.DataFrame(...)

def foo(x):
    if shoes in df_shoes_group_names:  # <-- THIS WILL NOT WORK
        # do something with x

良好做法

# dataframes
df_shoes_group_names = pd.DataFrame(...)
df_boots_group_names = pd.DataFrame(...)
df_sandals_group_names = pd.DataFrame(...)

dfs = {'shoes': df_shoes_group_names,
       'boots': df_boots_group_names,
       'sandals': df_sandals_group_names}

def foo(key):
    if 'shoes' in key:  # <-- THIS WILL WORK
        # do something with dfs[key]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多