我一直在尝试将一行中每个单元格的值与整数进行比较,如下所示:
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_csv为 DataFrame 添加参数 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
