从Python Pandas数据帧中的字符串中减去字符串

时间:2014-06-10 21:59:19

标签: python pandas

这是我的数据框:

    date item1 item2  item1 birth  item2 birth  item1 age  item2 age
0   1980     a     f         1975         1979          5          1
1   1980     a     f         1975         1979          5          1
2   1979     e     f         1979         1979          0          0
3   1979     e     f         1979         1979          0          0
4   1978     c     d         1976         1978          2          0
5   1977     a     b         1975         1975          2          2
6   1977     a     b         1975         1975          2          2
7   1975     a     b         1975         1975          0          0
8   1975     a     b         1975         1975          0          0
9   1977     b     a         1975         1975          2          2
10  1976     b     c         1975         1976          1          0

[11 rows x 7 columns]

这样做时: df2 = df[ df['date' - 'item1 birth'] <= 3 ]

我明白了: TypeError: unsupported operand type(s) for -: 'str' and 'str'

转而去: int('date') - int('item1 birth')

我明白了: ValueError: invalid literal for int() with base 10: 'date'

在做的时候: float('date') - float('item1 birth')

我最终得到: ValueError: could not convert string to float: date

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

假设数字dtype的列值,您可以这样减去列值:

mask = (df['date'] - df['item1 birth'] <= 3)
df2 = df.loc[mask]