gpt4 book ai didi

python - 将单元格值与 Pandas 中的整数进行比较,给出类型错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:04:30 26 4
gpt4 key购买 nike

我一直在尝试将一行中每个单元格的值与整数进行比较,如下所示:

df.loc[df['A'] <= 14, 'A']

所有值小于或等于 14 的行,但显示如下错误:

TypeError : '<=' is not supported between instances of str and int

最佳答案

你需要replace , 为空并转换为int:

df = pd.DataFrame({'A':['1,473','1,473','1,4', '1,2'],
'B':[2,4,5,5]})
print (df)
A B
0 1,473 2
1 1,473 4
2 1,4 5
3 1,2 5

df['A'] = df['A'].str.replace(',', '').astype(int)
s = df.loc[df['A'] <= 14, 'A']
print (s)
2 14
3 12
Name: A, dtype: int32

如果使用read_csvDataFrame 添加参数 thousands=',':

df = pd.read_csv(file, thousands=',', sep=';')

示例:

import pandas as pd
from pandas.compat import StringIO

temp=u"""A;B
1,473;2
1,473;4
1,4;5
1,2;5"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), thousands=',', sep=';')

print (df)
A B
0 1473 2
1 1473 4
2 14 5
3 12 5

s = df.loc[df['A'] <= 14, 'A']
print (s)
2 14
3 12
Name: A, dtype: int64

关于python - 将单元格值与 Pandas 中的整数进行比较,给出类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44874061/

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