gpt4 book ai didi

python - 使用 pandas dtype 作为条件

转载 作者:太空宇宙 更新时间:2023-11-03 13:57:59 25 4
gpt4 key购买 nike

我正在尝试从 pandas 数据框中某些列的字符串中删除某些字符。我在 for 循环中执行所有这些操作,因此我想在循环中使用 if 语句对所有“对象”dtype 列执行操作。

for col in pitchtype :
pitchtype[col] = pitchtype[col].replace(np.nan,0)
if pitchtype[col].dtype == 'object':
pitchtype[col] = pitchtype[col].map(lambda x: x.replace(' %',''))

是否有办法在 if 语句中实现该条件?

编辑:在下面添加了我的 DF。基本上,标题中带有 % 的列在值中有“%”符号,这会阻止它们 float 。我正在尝试删除“%”并将列更改为之后键入 float。

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 264 entries, 0 to 263

数据列(共18列):

Name        264 non-null object
Team 264 non-null object
FB% 264 non-null object
FBv 264 non-null float64
SL% 264 non-null object
SLv 264 non-null float64
CT% 264 non-null object
CTv 264 non-null float64
CB% 264 non-null object
CBv 264 non-null float64
CH% 264 non-null object
CHv 264 non-null float64
SF% 264 non-null object
SFv 264 non-null float64
KN% 264 non-null object
KNv 264 non-null float64
XX% 264 non-null object
playerid 264 non-null int64

dtypes: float64(7), int64(1), object(10)
memory usage: 37.2+ KB

最佳答案

我认为这可能是您正在寻找的,检查单个对象以查看它们是否为字符串。

if pitchtype[col].dtype == object: # No quotes around it!
pitchtype[col] = pitchtype[col].map(lambda x: x.replace(' %','') if type(x) == str else x)

关于python - 使用 pandas dtype 作为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52878191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com