Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a column value into dataframe dictionary using a for loop so that each dataframe gets a unique column?

I want to add the codes to the dataframe dictionary.

 codes = [['01', '02', '03', '05', '06', '08', '10', '11', '13', '15', '17', '19', '21', '23', '25', '27', '29', '31', '33', '35', '37', '39', '43', '45', '4.55', '48', '52']
 #27Codes

 df = pd.read_excel(sales,sheet_name=None,ignore_index = True, skiprows=7)
 #27 Sheets
 for i in codes:
      for key in df.keys():
          df['Sheet1']['Code'] = i

I can't figure out why I seem to have the i in every dataframe. I think I understand why I can't figure out how to correct it. I am a beginner at coding.

Expected output:

df['Sheet1']

   Date         Particulars    Inwards  Code

1 2017-04-01         EFG           12800    01
2 2017-07-22         ABC           100      01
3 2017-09-05         BCD           10000    01
4 2018-03-13         ABC           2000     01

Code column should be 02 in the next dataframe and so on.

After this I want to concat the dataframes and group_by particulars and then write to Excel.

like image 632
Sid Avatar asked Jan 03 '23 13:01

Sid


1 Answers

You can use a dictionary comprehension for this:

df = {k: v.assign(Code=x) for x, (k, v) in zip(codes, df.items())}

pd.DataFrame.assign allows you to add a series with a fixed value.

like image 176
jpp Avatar answered Jan 05 '23 04:01

jpp