首页 > 解决方案 > 使用 for 循环 python 创建和修改数据框

问题描述

我是 Python 和 StackOverflow 的新手。希望我发布正确:)

问题:在每个 for 循环中,我都试图创建一个新的数据框,向其中添加列,并用数据填充列。

方法:通过阅读以前的帖子,我了解到我可以使用“exec”创建新的数据帧,但这不是最佳实践。或者,我可以创建一个 dic 并在之后修改 df。也一直在尝试使用嵌入式 for 循环

问题:实际修改和填写创建的(和空的)df

代码:

df1 = an existing dataframe with date as its index and profit, tax, and revenue for columns 
#tablelist will only have these 4 values
tablelist = ['QTD','YTD','OneYear','Inception']

# Method 1
for table in tablelist:
     #this works
     exec('{} = pd.DataFrame()'.format(table))
     #this doesn't work 
     table['Value'] = df1[profit] - df1[tax]

---> error: 'str' object does not support item assignment

# Output (without line 4)

type(YTD)
pandas.core.frame.DataFrame

#this works but its outside of the loop so it defeats purpose
YTD['Value'] = df1[profit] - df1[tax]                           

方法 1 没有帮助,因为它在循环之外。

# Method 2
d = {}
for i in tablelist1:
    #this works but I cant figure out how add columns and data
    d[i] = pd.DataFrame()

# Output

print(d)

{'QTD': Empty DataFrame
 Columns: []
 Index: [], 'YTD': Empty DataFrame
 Columns: []
 Index: [], 'OneYear': Empty DataFrame
 Columns: []
 Index: [], 'Inception': Empty DataFrame
 Columns: []
 Index: []}

方法 2 有效,但如何添加列和数据?

任何意见是极大的赞赏!!

标签: pythonpandasdataframedictionaryfor-loop

解决方案


第二种方法应该在python中使用。因为定义在一个明确的地方。此外,变量的范围尽可能大。您可以通过查找字典的键轻松查找定义的数据帧。
您可以通过索引添加新列:

d = {}
for i in tablelist1:
    d[i] = pd.DataFrame()
    d[i]['Value'] = df1["profit"] - df1["tax"]

第一种方法使用表数组给定的名称创建全局变量。因此,如果您想追加新列。您不会使用 table 作为数据框的变量名称,而是使用字符串给出的名称。再次与执行官有关。这种方式我不推荐,因为变量被定义为全局变量,而且它们的定义方式非常隐蔽。请参阅以下内容:

import pandas as pd

tablelist = ['QTD','YTD','OneYear','Inception']

for table in tablelist:
    exec('{} = pd.DataFrame()'.format(table))
    exec(table + "['col1'] = []")

print(QTD) # or others

推荐阅读