【问题标题】:Pandas: modify multiple dataframes (in a loop)熊猫:修改多个数据帧(循环)
【发布时间】:2020-06-05 13:55:11
【问题描述】:

我有多个数据框,我想为它们执行相同的功能。因此我需要迭代我的框架。

# read text files 
df1 = pd.read_csv("df1.txt", sep="\t", error_bad_lines=False, index_col =None)
df2 = pd.read_csv("df2.txt", sep="\t", error_bad_lines=False, index_col =None)
df3 = pd.read_csv("df3.txt", sep="\t", error_bad_lines=False, index_col =None)

我使用了以下代码,但是,它不起作用(这意味着所有数据帧仍然相同,并且更改不会影响它们):

for df in [df1 , df2 , df3]:
    df = df[df["Time"]>= 600.0].reset_index(drop=True)
    df.head()

我如何迭代它们?以及如何覆盖数据帧?

【问题讨论】:

  • 这是因为您只在循环中修改数据帧,而不是覆盖列表中的数据帧。
  • _ 它不工作:_ 这是什么意思?你做过调试吗?请提供minimal reproducible example,以及对问题的清晰描述。见How to Askhelp center
  • @Erfan,是的,那我怎么覆盖呢?

标签: python pandas


【解决方案1】:

问题在于您没有更改数据框,而是创建新的数据框。这是一段就地改变事物的代码。我没有你的数据,所以为了这个例子我创建了假数据:

df1 = pd.DataFrame(range(10))
df2 = pd.DataFrame(range(20))
df3 = pd.DataFrame(range(30))
df_list = [df1, df2, df3]

for df in df_list: 
    # use whatever condition you need in the following line
    # for example, df.drop(df[df["Time"] < 600].index, inplace=True)
    # in your case. 
    df.drop(df[df[0] % 2 == 0].index, inplace=True)
    df.reset_index(inplace = True)

print(df2) # for example

df2 的结果是:

   index   0
0      1   1
1      3   3
2      5   5
3      7   7
4      9   9
5     11  11
6     13  13
7     15  15
8     17  17
9     19  19

【讨论】:

  • 是的,我需要更改数据框,但是如何?对于“drop”,您可以使用“inplace”。但是,我想写 "df[df["Time"]>= 600.0]" ,它没有 inplace 方法。
  • 这是低于 600 的所有内容的“下降”,不是吗?
  • 如果它回答了您的问题,请告诉我。
  • 是的,它适用于放置。但我还需要稍后将它们归为没有到位的地方。但是,您对此示例的解决方案有效,谢谢
【解决方案2】:

这可能有效:

df_list=[df1,df2,df3]

for df in range(len(df_list)):
    df=df_list[i]
    df_list[i]=df[df["Time"]>=600.0].reset_iundex(drop=True)

【讨论】:

  • 这不会改变原始数据框。只是列表。
  • 它在“for”行中产生这个错误:'int' object is not iterable
【解决方案3】:

如果您只是将新的 df 存储到另一个列表或同一个列表中,那么一切都很好。

newdf_list = []                                 # create new list to store df
for df in [df1 , df2 , df3]:
    df = df[df["Time"]>= 600.0].reset_index(drop=True)
    df.head()
    newdf_list.append(df)                       # append changed df to new list

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2021-12-22
    • 2017-01-11
    • 2018-02-11
    相关资源
    最近更新 更多