赞
踩
a b c
0 0 2 4
1 6 8 10
2 12 14 16
3 18 20 22
4 24 26 28
5 30 32 34
6 36 38 40
df[df['a']>30] # 筛选a列的取值大于30的记录,但只显示满足条件的b,c列的值 df[['b','c']][df['a']>30] # 使用isin函数根据特定值筛选记录。筛选a值等于30或者54的记录 df[df.a.isin([30, 54])] # 选择时间小于10秒的行 time_series = time_series[time_series.index < timedelta(seconds=10)] c2 = c1[c1.values == class_num] #过滤掉为 0 的行 data = df[df[self.time_col].apply(lambda x: str(x)) != '0'] print(df[df["Supplier Name"].str.contains('Z')]) print(df[df['Cost'].str.strip('$').astype(float) > 600]) #行中的值匹配某个模式 print(df[df['Invoice Number'].str.startswith("001-")])
可以使用&(并)与| (或)操作符或者特定的函数实现多条件筛选
# 使用&筛选a列的取值大于30,b列的取值大于40的记录
df[(df['a'] > 30) & (df['b'] > 40)]
# 多条件筛选 + 索引重置
data = meso_data[(self.meso_data['time'] >= start_date) & (self.meso_data['time'] <= end_date)].reset_index(drop=True)
df[行索引,列索引]或df[[列名1,列名2]]
# 使用切片操作选择特定的行
df[1:4]
#传入列名选择特定的列
df[['a','c']]
当每列已有column name时,用 df [ ‘a’ ] 就能选取出一整列数据。如果你知道column names 和 index,且两者都很好输入,可以选择 .loc同时进行行列选择。
In [28]: df.loc[0, 'c'] Out[28]: 4 In [29]: df.loc[1: 4, ['a','c']] Out[29]: a c 1 6 10 2 12 16 3 18 22 4 24 28 In [30]: df.loc[[1,3,5], ['a','c']] Out[30]: a c 1 6 10 3 18 22 5 30 34 df = df.loc[(df['行业编码'] == 1) & (df['单位编码'] == 102)] use_df = tenmin.loc[(tenmin['状态'] == 5) & (tenmin['模式'] == 0) & (tenmin['完整率'] >= 0.9)] # 根据某两列条件选择数据,然后索引重置 Data= Data.loc[(Data['num'] >= 0) & (Data['num'] <= 70)].reset_index(drop=True) df.loc[df[ws_name] > CutOutWS, power_name] = 0 ws_ym_ak.loc[(ws_ym_ak.year == date[0]) & (ws_ym_ak.month == date[1]), 'A'].values[0] Out[112]: 7.2683892675086845 ws_ym_ak.loc[(ws_ym_ak.year == date[0]) & (ws_ym_ak.month == date[1]), 'K'].values[0] Out[113]: 3.97522610048051 #按时间过滤行,同时选择['time', 'filled_ws']两列 construct_ws = target.loc[(target['time'] >= start) & (target['time'] < end), ['time', 'filled_ws']] #取一个值,行满足year=date[0],month=date[1]时,第'A'列对应的值。 ws.loc[(ws.year == date[0]) & (ws.month == date[1]), 'A'].values[0] ws.loc[(ws.year == date[0]) & (ws.month == date[1]), 'A'].values #是一个<class 'numpy.ndarray'> ws.loc[(ws.year == date[0]) & (ws.month == date[1]), 'A'] #是一个<class 'pandas.core.series.Series'> temp = (Data['wtb_std'] < firm_wd_std) & (Data['wrf_std'] < firm_wd_std) # bool型结果 Merged_Data = Data.loc[temp, :] # 根据上面的bool结果,筛选数据 data = data.loc[data['std']>0, :] #过滤之后再求mean均值 test = np.mean(repr_year.loc[(repr_year['信息时间'] >= turbine_info['ays_start']) & (repr_year['信息时间'] >= pd.to_datetime(turbine_info['ays_end'])), 'ws_mean'].values) test = repr_year.loc[(repr_year['信息时间'] >= turbine_info['ays_start']) & (repr_year['信息时间'] <= pd.to_datetime(turbine_info['ays_end'])), 'ws_mean'].mean() x_1 = sales_train_validation.loc[sales_train_validation['id'] == ids[2]].set_index('id')[d_cols].values[0] df.loc[(df["Supplier Name"].str.contains('Z'))|(df['Cost'].str.strip('$').astype(float) > 600.0), :] li = [2341, 6650] print(df[df['Part Number'].isin(li)]) print(df.loc[df['Part Number'].astype(int).isin(li), :]) #选取特定的列 #列标题打印 print(df.loc[:,["Invoice Number", "Part Number"]]) #选取连续的行 print(df.loc[1:4, :])
如果column name太长,输入不方便,或者index是一列时间序列,更不好输入,那就可以选择 .iloc了,该方法接受列名的index,iloc 使得我们可以对column使用slice(切片)的方法对数据进行选取。这边的 i 我觉得代表index,比较好记点。
In [35]: df.iloc[0, 2] Out[35]: 4 In [34]: df.iloc[1: 4, [0,2]] Out[34]: a c 1 6 10 2 12 16 3 18 22 In [36]: df.iloc[[1,3,5], [0,2]] Out[36]: a c 1 6 10 3 18 22 5 30 34 In [38]: df.iloc[[1,3,5], 0:2] Out[38]: a b 1 6 8 3 18 20 5 30 32 start = temp_df[target_col].iloc[0] end = temp_df[target_col].iloc[-1] #直接用iloc选择某行 production_end = pd.to_datetime(data[time_col].iloc[-1]) #列索引值,打印1,3列 print(df.iloc[:, 1:4:2])
ix的功能更加强大,参数既可以是索引,也可以是名称,相当于,loc和iloc的合体。需要注意的是在使用的时候需要统一,在行选择时同时出现索引和名称, 同样在同行选择时同时出现索引和名称。
df.ix[1: 3, ['a','b']] Out[41]: a b 1 6 8 2 12 14 3 18 20 In [42]: df.ix[[1,3,5], ['a','b']] Out[42]: a b 1 6 8 3 18 20 5 30 32 In [45]: df.ix[[1,3,5], [0,2]] Out[45]: a c 1 6 10 3 18 22 5 30 34
根据指定行index及列label,快速定位DataFrame的元素,选择列时仅支持列名。
In [46]: df.at[3, 'a']
Out[46]: 18
与at的功能相同,只使用索引参数
In [49]: df.iat[3,0]
Out[49]: 18
python筛选列表中大于0的数据的方法:
1、使用匿名函数lambda和filter函数筛选列表中大于0的数据
Ldata = [1, 2, 3, 4, 5, 6, -1, -2]
res1 = list(filter(lambda x: x > 0, Ldata))
print(res1)
输出结果如下:
[1, 2, 3, 4, 5, 6]
#挑选df中,每行全部大于0,的行
df0 = df[df.apply(lambda x: len(list(filter(lambda y: y > 0, x))) == len(x), axis=1)]
# 差分后,剔除全为正之后
df_1 = df[df.apply(lambda x: len(list(filter(lambda y: y > 0, x[:5]))) >= 4, axis=1)]
2、使用列表解析筛选列表中大于0的数据
Ldata = [1, 2, 3, 4, 5, 6, -1, -2]
res1 = [x for x in Ldata if x > 0]
print(res1)
输出结果如下:
[1, 2, 3, 4, 5, 6]
df 是包含多个列的 dataframe,且其值只包括 False 和 True 两种。下面代码的作用是,删除全为False的行。
df_filtered = df[~(df == False).all(axis=1)]
参考链接:
[1] python怎么筛选列表中大于0的数据?2020.5
[2] python之pandas数据筛选和csv操作 2019.8
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。