简体   繁体   English

遍历不同的数据帧

[英]loop over different dataframes

I have 59 different dataframes of different participants.我有 59 个不同参与者的不同数据框。 Each participants has his/her own dataframe because that is necessary for splitting the right way in train and test groups later on.每个参与者都有他/她自己的数据框,因为这对于稍后在训练和测试组中以正确的方式划分是必要的。

Now I want to add a new column AcuteLegs_3days , which I knew works like this:现在我想添加一个新列AcuteLegs_3days ,我知道它是这样工作的:

trainingload['AcuteLegs_3days']=trainingload["AcuteLegs_1day"].rolling(3).sum()
trainingload['AcuteLegs_3days']=trainingload['AcuteLegs_3days'].shift(1)

But can I do this for all 59 dataframes at once?但是我可以一次对所有 59 个数据帧执行此操作吗?

I have a list of all dataframe names:我有所有数据框名称的列表:

participants = ['df_participant1', 'df_participant2', ...]

I tried to build a for loop but it is not working我试图构建一个 for 循环,但它不起作用

for df in participants:
    df['AcuteLegs_3days']=df["AcuteLegs_1day"].rolling(3).sum()
    df['AcuteLegs_3days']=df['AcuteLegs_3days'].shift(1)

this gives the error:这给出了错误:

TypeError: string indices must be integers类型错误:字符串索引必须是整数

Your participants list is a list of strings, not a list of actual dataframes.您的参与者列表是字符串列表,而不是实际数据框列表。

You can either create a list of dataframes, removing quotes:您可以创建数据框列表,删除引号:

participants = [df_participant1, df_participant2, ...]

and continue as you do now or get dataframe from locals (as I proposed in comments):并像现在一样继续或从当地人那里获取数据框(正如我在评论中提出的那样):

for df_name in participants: 
    df = locals()[df_name]
    df['AcuteLegs_3days']=df["AcuteLegs_1day"].rolling(3).sum()
    df['AcuteLegs_3days']=df['AcuteLegs_3days'].shift(1)

Currently you're trying to use strings as dataframes, which obviously fails (eg you have a list of names, not variables).目前您正在尝试使用字符串作为数据框,这显然会失败(例如,您有一个名称列表,而不是变量)。 So you try to execute the following:因此,您尝试执行以下操作:

'df_participant1'['AcuteLegs_3Days']

and strings can be indexed only by integers (well, strictly speaking, anything with __index__ defined) or slices.并且字符串只能由整数(严格来说,任何定义了__index__的东西)或切片索引。 You cannot say 'foo'['bar'] , because it simply makes no sense.你不能说'foo'['bar'] ,因为它根本没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM