Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

dataframe - How to pad 0's in the pandas data frame?

I want to fill 0's in those cluster names that are not present. As in the expected output, I have added 0 in the last row because I didn't find any result of that in the dataframe. Input:

I have tried so far

#I have made clusters according to the requirement and making sum of it
# output of this code is given above
d_inv = {x: k for k, v in dict1.items() for x in v}
df = df['PII Count'].groupby(df['PII'].map(d_inv)).sum() 
        .rename_axis('Cluster names') 
        .reset_index(name='Total count')
print(df)
question from:https://stackoverflow.com/questions/65941122/how-to-pad-0s-in-the-pandas-data-frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If order doesnot matter use a reindex and make use of the keys from dict1:

(df['PII Count'].groupby(df['PII'].map(d_inv)).sum().rename_axis('Cluster names')
                .reindex(dict1.keys(),fill_value=0)
                .reset_index(name='Total count'))

   Cluster names  Total count
0  Personal Info          270
1    Health Info            0
2   Network Info           94
3    Others Info           59
4   Finance Info            1

If Order matters:

m = df['PII'].map(d_inv)
out = df['PII Count'].groupby(m).sum()
out = (out.reindex(out.index.union(set(dict1.keys()).difference(m),sort=False),
        fill_value=0)
        .rename_axis('Cluster names')
        .reset_index(name='Total count'))

print(out)

   Cluster names  Total count
0   Finance Info            1
1   Network Info           94
2    Others Info           59
3  Personal Info          270
4    Health Info            0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...