简体   繁体   中英

Keeping merged cells in excel and pasting df into certain cells and columns

I am currently trying to fill empty cells with 1, and keeping the cells with string values (eg. S,R,G,B).

My data source is an excel file which has the following.

Raw Data:

Customer ID      1      2    3    4
0010                    R    G    G
                 S      A    A
0599             R                B
0442             A      B  

*Note that 0010 is a merged cell, while columns 1,2,3,4 is not merged.

Intended Output Data

Customer ID      1     2    3    4
0010             1     R    G    G
 1               S     A    A    1
0599             R     1    1    B
0442             A     B    1    1

I would like to keep the merged "Customer ID". Is there any way to work around this? And also can I set the function to apply to only certain rows and columns? And also to paste the df back to certain rows and columns?

Current Code:

data = pd.read_excel('path',header=0)
df = pd.DataFrame(data)

df= df.fillna(1)

df.to_excel('path', index=False)

Try specifying that the Customer ID field is an object . This should then result in empty values appearing as Nan . Then the fillna() should work as expected:

import pandas as pd

df = pd.read_excel('path.xlsx', header=0, dtype={'Customer ID':object})

print(df)
df = df.fillna('1')
print(df)

df.to_excel('path_out.xlsx', index=False)

This would display:

  Customer ID    1    2    3    4
0        0010  NaN    R    G    G
1         NaN    S    A    A  NaN
2        0599    R  NaN  NaN    B
3        0442    A    B  NaN  NaN

  Customer ID  1  2  3  4
0        0010  1  R  G  G
1           1  S  A  A  1
2        0599  R  1  1  B
3        0442  A  B  1  1

If Customer ID is a merged cell eg merging A and B , then you could skip over the merged column as follows:

df = pd.read_excel('path.xlsx', usecols="A,C:F", header=0, dtype={'Customer ID':object})

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