-1

Consider I have multiple lists

A = ['acc_num=1', 'A1', 'A2']
B = ['acc_num=2', 'B1', 'B2', 'B3','B4']
C = ['acc_num=3', 'C1']

How to I put them in dataframe to export to excel as:

   acc_num     _1  _2  _3  _4  
_1 1           A1  A2
_2 2           B1  B2  B3  B4
_3 3           C1
Kazien
  • 33
  • 7
  • Does this answer your question? [add columns different length pandas](https://stackoverflow.com/questions/27126511/add-columns-different-length-pandas) – Björn Apr 25 '20 at 08:51
  • Or [here](https://stackoverflow.com/questions/49891200/generate-a-dataframe-from-list-with-different-length). [Another Question](https://stackoverflow.com/questions/53300698/how-to-make-different-length-list-to-a-single-dataframe-in-python). Here are some more [solutions](https://stackoverflow.com/questions/19057052/create-a-dataframe-from-a-list-of-length-unequal-lists) took me maybe 5 seconds to find these. – Björn Apr 25 '20 at 08:52
  • I have done search before asking. Checked your three links. I am new to python and I know this is a very simple question. I am getting the lists A, B and C from the result of a for loop. I want to append the lists into a dataframe so I can save to excel. I have the code for ExcelWriter already. – Kazien Apr 25 '20 at 09:04
  • Ok sorry I didn't mean to be rude... gonna try to help you – Björn Apr 25 '20 at 09:07
  • The dataframe manipulation is quite complicated. I am even not sure how to add list or dataframe to a datafrme. There can be append and concat. – Kazien Apr 25 '20 at 09:12
  • Did my answer solve your issue? Please consider accepting the answer when it solved the problem since this makes it visible to others searching for a similar problem – Björn Apr 25 '20 at 10:55

1 Answers1

0

Hi here is a solution for you in 3 basic steps:

  1. Create a DataFrame just by passing a list of your lists
  2. Manipulate the acc_num column and remove the starting string "acc_num=" this is done with a string method on the vectorized column (but that goes maybe to far for now)
  3. Rename the Column Header / Names as you wish by passing a dictionary {} to the df.rename

The Code:

# Create a Dataframe from your lists
df = pd.DataFrame([A,B,C])
# Change Column 0 and remove initial string
df[0] = df[0].str.replace('acc_num=','')
# Change the name of Column 0
df.rename(columns={0:"acc_num"},inplace=True)

Final result:

Out[26]: 
  acc_num   1     2     3     4
0       1  A1    A2  None  None
1       2  B1    B2    B3    B4
2       3  C1  None  None  None
Björn
  • 1,610
  • 2
  • 17
  • 37