Python/if语句和索引
我相信这个问题有一个简单的解决办法,但我似乎找不到 我试图检查列表中的年龄是否在我的数据框的年龄列中。但是,它只是与索引进行比较,而不是与列进行比较 下面是我程序中的一段简化代码:Python/if语句和索引,python,function,pandas,if-statement,dataframe,Python,Function,Pandas,If Statement,Dataframe,我相信这个问题有一个简单的解决办法,但我似乎找不到 我试图检查列表中的年龄是否在我的数据框的年龄列中。但是,它只是与索引进行比较,而不是与列进行比较 下面是我程序中的一段简化代码: def findages(data,ages): for age in ages: if age in data['age']: print('yes') else: print('no') 我也试过: def findages
def findages(data,ages):
for age in ages:
if age in data['age']:
print('yes')
else:
print('no')
我也试过:
def findages(data,ages):
for age in ages:
if age in data.loc[data['age']]:
print('yes')
else:
print('no')
数据帧如下所示
age x Lambda L
0 1.258930e+05 0.01 91.0 5.349000e+25
1 1.258930e+05 0.01 94.0 1.188800e+26
2 1.258930e+05 0.01 96.0 1.962700e+26
3 1.258930e+05 0.01 98.0 3.169400e+26
4 1.258930e+05 0.01 100.0 5.010800e+26
列表如下:
ages = ([125893.0, 4e7,5e9])
我做错了什么 用于:
样本:
import pandas as pd
import numpy as np
data = pd.DataFrame({'age':[10,20,30]})
ages = [10,30]
print (data)
age
0 10
1 20
2 30
data['new'] = np.where(data['age'].isin(ages),'yes','no')
print (data)
age new
0 10 yes
1 20 no
2 30 yes
按示例编辑:
print (data)
age x Lambda L
0 125893.0 0.01 91.0 5.349000e+25
1 125893.0 0.01 94.0 1.188800e+26
2 125893.0 0.01 96.0 1.962700e+26
3 125893.0 0.01 98.0 3.169400e+26
4 125893.0 0.01 100.0 5.010800e+26
ages = ([125893.0, 4e7,5e9])
print (np.where(data['age'].isin(ages),'yes','no'))
['yes' 'yes' 'yes' 'yes' 'yes']
DataFrame列访问返回一个系列
在代码中,data['age']
返回一系列列age
。在这种情况下,中的运算符将与索引进行比较。要与序列中的值进行比较,请使用.values
属性获取序列值的数组
举例来说:
您能提供一个示例输入吗?只是更新了问题,不用担心,需要一些经验来使用库的接口和功能。坚持下去,这是一个非常有用的工具!
print (data)
age x Lambda L
0 125893.0 0.01 91.0 5.349000e+25
1 125893.0 0.01 94.0 1.188800e+26
2 125893.0 0.01 96.0 1.962700e+26
3 125893.0 0.01 98.0 3.169400e+26
4 125893.0 0.01 100.0 5.010800e+26
ages = ([125893.0, 4e7,5e9])
print (np.where(data['age'].isin(ages),'yes','no'))
['yes' 'yes' 'yes' 'yes' 'yes']
import pandas as pd
df = pd.DataFrame({'age':[33, 34], 'pet':['Dog', 'Cat']}, index=['Bob', 'Mary'])
ages = [5, 33, 67]
def findages(data, ages):
for age in ages:
if age in data['age'].values:
print('yes')
else:
print('no')
findages(df, ages)
no
yes
no