Python Append dataframe generated in nested loops

2024/9/20 8:49:04

My program has two for loops. I generate a df in each looping. I want to append this result. For each iteration of inner loop, 1 row and 24 columns data is generated. For each iteration of outer loop, it generates 8 rows 24 columns data. I am having issues in appending in the right way so the final dataframe has 8 rows and 24 columns. My code:

biglist = []
# The actual code is bigger. Below is representation of it.
for i in range (x1,...,x8):tem_list = []for j in range ([y1,y2,y3],[y4,..]...[y22,y23,y24]):tem_df = pd.DataFrame({'y1':[value1],'y2':[value2],'y3':[value3]},index=i)tem_list.append(tem_df)biglist.append(tem_list)
# convert listss of lists in biglist to a simple list of dfs
biglist1 = [item for sublist in biglist for item in sublist]
df = pd.concat(biglist1)
print(df)

Present output:

# below is actual output of my dataframe: Pmpp_loss Pmpp_delmt  ... Rsh_delmt Rsh_desen
s1    17.0326    42.5349  ...       NaN       NaN
s2        NaN        NaN  ...       NaN       NaN
s3        NaN        NaN  ...       NaN       NaN
s4        NaN        NaN  ...       NaN       NaN
s5        NaN        NaN  ...       NaN       NaN
s6        NaN        NaN  ...       NaN       NaN
s7        NaN        NaN  ...       NaN       NaN
s8        NaN        NaN  ...   92.1853 -0.444959[8 rows x 192 columns]

In the above, 8 rows is correct. But I got 192 columns, instead of 24. Here, 24 columns got repeated 8 times. That is the reason we see many NaNs here.

Answer

Try:

  • Change this biglist.append(tem_list) to this: biglist.append(pd.concat(tem_list)).

  • Remove this line: biglist1 = [item for sublist in biglist for item in sublist]

  • Modify this one df = pd.concat(biglist1) to df = pd.concat(biglist)


If you have defined column names, you can also create an empty DataFrame outside your looping scope, and append the data directly on it from your inner loop:

# Before loop
colnames = ['y1', 'y2', 'y3']
df = pd.DataFrame(data=None, columns=colnames)

chaging your append lines to a single one inside your inner loop:

df = df.append(tem_df)

Not needed the use of biglist, tem_list or pd.concat.


Edit after user comments:

biglist = []
for i in range (x1,...,x8):for j in range ([y1,y2,y3],[y4,..]...[y22,y23,y24]):tem_df = pd.DataFrame({'y1':[value1],'y2':[value2],'y3':[value3]},index=i)biglist.append(pd.concat(tem_df),axis=1)
df = pd.concat(biglist)
print(df)
https://en.xdnf.cn/q/119385.html

Related Q&A

bError could not find or load main class caused by java.lang.classnotfoundation error

I am trying to read the executable jar file using python. That jar file doesnt have any java files. It contains only class and JSON files. So what I tried is from subprocess import Popen,PIPEjar_locati…

Invalid value after matching string using regex [duplicate]

This question already has answers here:Incrementing a number at the end of string(2 answers)Closed 3 years ago.I am trying to match strings with an addition of 1 at the end of it and my code gives me t…

How to fetch specific data from same class div using Beautifulsoup

I have a link : https://www.cagematch.net/?id=2&nr=448&gimmick=Adam+Pearce In this link there data in divs with same class name. But I want to fetch specifi div. Like I want to fetch current g…

Python Matplotlib Box plot

This is my dataframe:{Parameter: {0: A, 1: A, 2: A, 3: A, 4: A, 5: A, 6: A, 7: A},Site: {0: S1,1: S2,2: S1,3: S2,4: S1,5: S2,6: S1,7: S2},Value: {0: 2.3399999999999999,1: 2.6699999999999999,2: 2.560000…

How to send turtle to random position?

I have been trying to use goto() to send turtles to a random position but I get an error when running the program.I am lost on how else to do this and not sure of other ways. My current code is:t1.shap…

How to scrape all p-tag and its corresponding h2-tag with selenium?

I want to get title and content of article: example web :https://facts.net/best-survival-movies/ I want to append all p in h2[tcontent-title]and the result expected is: title=[title1, title2, title3]co…

Tkinter: Window not showing image

I am new to GUI programming and recently started working with tKinter.My problem is that the program wont show my image, Im suspecing that it is my code that is wrong, however, I would like somone to e…

print dictionary minus two elements

Python 3.6All debug output is from PyCharm 2017.1.2I have a program that gets to this portion of the code:if len(errdict) == 21:for k, v in errdict.items():if k == packets output or bytes:continueprint…

Write CSV file using Python with the help of a csv dictionary / nested csv dictionary

I am having a csv file and i want to write it to another csv file. Its a bit complicated than it seems. Hoping someone to correct my code and rewrite it, so that i can get the desired csvfile. I am usi…

saving data to txt file using python

I am new in python, and I really need some help. I am doing this memory game where I need to save user, game score and time into a text file using python. I have tried several ways to do it, but nothin…