【问题标题】:how to change dataframes using a loop in Python Pandas? [duplicate]如何在 Python Pandas 中使用循环更改数据框? [复制]
【发布时间】:2018-01-06 20:20:19
【问题描述】:

我有 N 个数据帧,范围从 L1...Ln。

我想修改它们以保持与特定条件相关的行。

我运行了以下循环:

for df in [L1,...,Ln]:
    df=df.ix[df['Sector']=='Services']

但是,当我调出每个数据框时,我发现它并没有被相应地替换。如何使用循环修改一组数据帧?

我使用的是 Python 2.7。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你需要用新的数据框覆盖旧的数据框:

    all_dfs = [L1,...,Ln]
    # iterate through the dataframes one by one
    # keep track of the order in index and the content in df 
    for index, df in enumerate(all_dfs):
        # modify the current dataframe df 
        # then overwrite the old one in the same index. 
        all_dfs[index]= df.ix[df['Sector']=='Services']
    

    【讨论】:

    • 我目前不是通过 df=df... 这样做吗?
    • @runawaykid 您正在覆盖局部变量 df。但不是列表中的实际 df。
    • 我发现我需要在最后添加行 [L1,...Ln] = all_dfs 才能在我调用 L1 时起作用。如果不是,它仍然是原始数据框。
    • @runawaykid 当然,因为 all_dfs 是 [L1,...Ln] 的副本。无论如何,您必须将列表 [L1,...Ln] 分配给一个变量并使用该变量而不是列表..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 2021-10-07
    相关资源
    最近更新 更多