python - 在 python pandas 过滤器中编辑数据并将其应用于原始数据框
问题描述
我试图弄清楚如何过滤熊猫中的数据,然后为符合过滤条件的项目的列中的所有行分配一个值,并让它影响原始数据框。这是迄今为止我最接近的尝试,但它引发了很多信息警告:
import pandas as pd
df = pd.read_csv('http://www.sharecsv.com/dl/9096d32f98aa0ac671a1cca16fa43be8/SalesJan2009.csv')
df['Zone'] = ''
zone1 = df[(df['Latitude'] > 0) & (df['Latitude'] > 0)]
zone2 = df[(df['Latitude'] < 0) & (df['Latitude'] > 0)]
zone3 = df[(df['Latitude'] > 0) & (df['Latitude'] < 0)]
zone4 = df[(df['Latitude'] < 0) & (df['Latitude'] < 0)]
zone1[['Zone']] = zone1[['Zone']] = 1
zone2[['Zone']] = zone1[['Zone']] = 2
zone3[['Zone']] = zone1[['Zone']] = 3
zone4[['Zone']] = zone1[['Zone']] = 4
df
这根本不会影响原始数据框,但会设置过滤子集中的值。
我假设我可能需要过滤掉符合每个过滤器的所有内容并将其从原始文件中删除,然后将更改连接回原始文件?
这是一个随机数据集,用于说明我想要做什么,但我的实际数据集包含不符合任何过滤条件的数据,我也需要将这些数据保持为未知,因为我不会像使用这个一样消耗所有行例子。
我试图避免遍历每一行并检查每一行的标准,所以如果有人知道我如何做到这一点,我将非常感激!
解决方案
IIUC,您是否正在尝试做这样的事情:
zone1 = (df['Latitude'] > 0) & (df['Longitude'] > 0)
zone2 = (df['Latitude'] < 0) & (df['Longitude'] > 0)
zone3 = (df['Latitude'] > 0) & (df['Longitude'] < 0)
zone4 = (df['Latitude'] < 0) & (df['Longitude'] < 0)
df['Zone'] = np.select([zone1,zone2,zone3,zone3],['Zone 1','Zone 2', 'Zone 3','Zone 4'])
输出:
Transaction_date Product Price Payment_Type Name \
0 1/2/09 6:17 Product1 1200 Mastercard carolina
1 1/2/09 4:53 Product1 1200 Visa Betina
2 1/2/09 13:08 Product1 1200 Mastercard Federica e Andrea
3 1/3/09 14:44 Product1 1200 Visa Gouya
4 1/4/09 12:56 Product2 3600 Visa Gerd W
City State Country Account_Created \
0 Basildon England United Kingdom 1/2/09 6:00
1 Parkville MO United States 1/2/09 4:42
2 Astoria OR United States 1/1/09 16:21
3 Echuca Victoria Australia 9/25/05 21:13
4 Cahaba Heights AL United States 11/15/08 15:47
Last_Login Latitude Longitude Zone
0 1/2/09 6:08 51.500000 -1.116667 Zone 3
1 1/2/09 7:49 39.195000 -94.681940 Zone 3
2 1/3/09 12:32 46.188060 -123.830000 Zone 3
3 1/3/09 14:22 -36.133333 144.750000 Zone 2
4 1/4/09 12:45 33.520560 -86.802500 Zone 3
推荐阅读
- php - 如何将产品详细信息从网站分享到 Facebook 和 LinkedIn
- python-3.x - TypeError:“NoneType”对象在创建 RESTful API 后端时不可下标
- python - Python continue 语句在 while 循环中的问题
- java - WELD-001408:在注入点 [BackedAnnotatedField] @Inject 具有限定符 @Default 的类型 Logger 的依赖关系不满足
- javascript - 有没有办法检查子 div 的底部?
- .net - CsvHelper 包:.netcoreapp3.0 不支持?
- visual-studio-code - 如何使用键盘专注于 git commit 消息输入 VSCode?
- android - 如何在 Android 上解释 mobilenetv2 分割结果输出?
- java - WebClient 返回空响应的问题
- sass - 修改器的简单 Sass BEM 继承