使用WHILE循环组合多个数据帧



来自建议的更新代码的结果截图

"dlist"是数据帧中提供程序id的列表。我尝试对"dlist"使用while循环,但它只返回数组中最后一个提供程序id的值。在这种情况下是1005。我使用了append函数,但它什么也没做。提供者id 1000中的另外74行没有显示。如何将所有内容组合起来,以便显示从数据列表到684行的两个数字的值?

dlist = ["1000", "1005"]
final_list = pd.DataFrame()
index = 0
while index < len(dlist):
provider = dlist[index]

# Filter dentist (CHANGEABLE)
final_list = report_df[(report_df["provider_id"] == provider)]
# Sort values of the codes
final_list = final_list.sort_values(['codes','report_month'], ascending=True)
# Drop 'report_year' column
final_list = final_list.drop(['report_year'], axis = 1)
# Change 'report_month' numbers into month name
final_list = final_list.replace({'report_month': {1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November"}})
final_list.append(final_list)
index +=1

缺失值

当前代码的结果

您可以创建一个包含所有数据帧的列表,然后将它们连接起来。像前面一样,while循环有一个数据帧列表。

list_of_dfs = []

并且在index+=1之前将final_list添加到数据帧的列表中。

list_of_dfs.append(final_list)

您可能不想像final_list.append(final_list)那样追加。

最终,你可以进行

my_df_of_concern = pd.concat(list_of_dfs, index=0)

请参阅https://pandas.pydata.org/docs/reference/api/pandas.concat.html

您的问题是一次又一次地修改同一个变量。在您的代码中:

Line 1: while index < len(dlist):
Line 2:    provider = dlist[index]

Line 3:    # Filter dentist (CHANGEABLE)
Line 4:    final_list = report_df[(report_df["provider_id"] == provider)] # PROBLEM LINE
Line 5:    # MORE CODE
Line 6:    # MORE CODE
Line 7:    final_list.append(final_list)
Line 8:    index +=1

由于您的dlist具有["1000", "1005"],因此在第一次运行的第4行中,final_list具有provider_id == 1000所在的所有行。然后对它进行一些修改,然后在第7行中,将它附加到同一个对象。现在,final_list将拥有所有内容的2个副本,因为您正在执行final_list.append(final_list)

然后增加索引,对于提供者现在为1005的下一次迭代,再次执行第4行,其中final_list将被覆盖。这意味着存储在该变量中的所有以前的值不再存在,只存在provider_id == 1005的新值。

尝试像这样更改代码

while index < len(dlist):
provider = dlist[index]

# Filter dentist (CHANGEABLE)
report_list = report_df[(report_df["provider_id"] == provider)]
# Sort values of the codes
report_list = report_list.sort_values(['codes','report_month'], ascending=True)
# Drop 'report_year' column
report_list = report_list.drop(['report_year'], axis = 1)
# Change 'report_month' numbers into month name
report_list = report_list.replace({'report_month': {1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November"}})
final_list.append(report_list)
index +=1

report_list充当一个临时变量,它保存特定提供者的所有数据,然后在进行所有修改(如删除report_year列、排序等(后,将值附加到final_list。现在您将拥有跨多个迭代的数据。

此外,代替

while index < len(dlist):
provider = dlist[index]
index +=1

你可以这样做:

for provider in dlist:
# YOUR CODE where provider will be "1000" for 1st run and "1005" in second run

相关内容

最新更新