简体   繁体   中英

Create pandas dataframe column using another dataframe

bg_d = pd.read_excel(f, sheet_name=None, index_col=None, usecols="C:N", skiprows=23, nrows=8)
identifier = pd.read_excel(f, sheet_name=None, index_col=None, header=None, usecols="B", skiprows=13, nrows=1)

This results in two dictionaries of dataframes (one dataframe per sheet in excel), something like this:

bg_d: {
Sheet1: 1 2 3 4 5 6 7 8 9 10 11 12,
Sheet2: 1 2 3 4 5 6 7 8 9 10 11 12,
Sheet3: 1 2 3 4 5 6 7 8 9 10 11 12 }
# note - each column (1, 2,3 etc.) has my experimental numbers

identifier: {
Sheet1: Water Sample,
Sheet2: Glycerin,
Sheet3: Serum }

I want the final dataframe of each sheet to look like this:

Water Sample 1 2 3 4 5 6 7 8 9 10 11 12
Glycerin 1 2 3 4 5 6 7 8 9 10 11 12
Serum 1 2 3 4 5 6 7 8 9 10 11 12

I've tried this:

bg_sheets = []
for sheet, name in bg_d.items():
   for s, n in identifier.items():
      val = n.values[0][0]
      sheet["Plate"] = val
      bg_sheets.append(sheet)

But I get a string error:

Exception has occurred: TypeError
'str' object does not support item assignment

The error is caused by bg_d.items() returning key and value, so the sheet is a string, not a dataframe. And you just need single loop. The code will be like this:

bg_sheets = []
for name,sheet  in bg_d.items():
    n = identifier.get(name)
    val = n.values[0][0]
    sheet["Plate"] = val
    bg_sheets.append(sheet)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM