pandas 在不更改格式的情况下更改列值 [英] pandas to change the colum value withoutchanging the format

查看:49
本文介绍了 pandas 在不更改格式的情况下更改列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有10000行的Excel工作表. 我必须基于Colum2的值更改Colum5的值,并更新Excel工作表.

I have a Excel sheet with 10000 Rows. I have to change the value of a Colum5 based on value of Colum2 and update the excel sheet.

我可以使用以下方法更改值:

I am able to change the values using:

import numpy as np
df=pd.read_excel('part2.xlsx')
count=0

while (count<10000):
     if df['Grade'][count] == 'A' :
         #df.loc[df['Grade'][count]] = 'Good'
         df['Grade'][count] = 'Good'
         print(count)
         print(df['Grade'][count])
     count=count+1

df.to_excel('temp.xlsx')

问题是当我写到新的Excel工作表时,所有格式都消失了. 我想在相同的excelsheet中实现相同的功能,以便不删除格式.

The issue with this is as I am writing to a new Excel sheet all the formatting is gone. I want to achieve the same thing in the same excelsheet so that format is not removed.

2)将df.loc保留在这里有什么用?

2) is there any use in keeping the df.loc here?

推荐答案

通过使用.loc

df=pd.DataFrame({'Grade':['A','B','C','A','D']})
df.loc[(df.Grade=='A')&(df.index<3),'Grade']='Good'
df
Out[489]: 
  Grade
0  Good
1     B
2     C
3     A
4     D

更多信息

(df.Grade=='A')&(df.index<3)
Out[296]: 
0     True
1    False
2    False
3    False
4    False
Name: Grade, dtype: bool

这篇关于 pandas 在不更改格式的情况下更改列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆