简体   繁体   English

如何在Python中切片列表

[英]How to slice lists in Python

I am at the trying to clean some data for a log regression in python and my list keeps showing up like 我正在尝试清理一些数据以进行python中的对数回归,并且我的列表不断显示

loansData['FICO.Score'][0:5]
Out[23]: 
81174    735-739
99592    715-719
80059    690-694
15825    695-699
33182    695-699

I want to be able to pick the lower fico range number how do I remove the first set of numbers and also remove the upper range? 我希望能够选择较低的fico范围数字,如何删除第一组数字并同时删除较高的范围?

It doesn't look like your Q's subject is germane to what you're actually asking about -- you're doing fine with the slicing of that one list, now what you have are, instead, strings (each an item from said list). 看来您的Q主题与您实际询问的内容并不相关-对该列表的切片您做得很好,现在您拥有的是字符串 (列表中的每一项) )。

Anyway, assuming eg the first one is 81174 735-739 (exactly four spaces in the middle, none before, no tab, &c), the 735 is the string slice at [9:12]. 无论如何,假设第一个是81174 735-739 (中间恰好有四个空格,之前没有,没有制表符,&c),则735是位于[9:12]的字符串片段。 So for example 所以举个例子

[s[9:12] for s in loansData['FICO.Score'][0:5]]

should show what you want (could easily need tweaking by 1 or so if the hypotheses above about the extract string format are incorrect, but, that's the general idea). 应该显示您想要的内容(如果上面关于提取字符串格式的假设不正确,则很容易需要将其微调1左右,但这是一般的想法)。

这是一个示例,该示例会将您的数据子集化为仅包含FICO观测值(含“ 695-699”,“ 690-694”分数)。

loansData['FICO.Score'][loansData['FICO.Score'].isin(['695-699', ' 690-694'])]

This answer assumes the 5 digit number is the series index, and you want to return an array with the lower bound of each value. 该答案假定5位数字是序列索引,并且您要返回一个数组,每个数组的下限均较低。

import pandas as pd

data: 数据:

i=[81174,99592,80059,15825,33182]
d = ['735-739','715-719','690-694','695-699','695-699']

recreate frame: 重新创建框架:

df =pd.DataFrame(d, index=i, columns=['FICO.Score'])

slice string and convert to int: 分割字符串并转换为int:

df['FICO.Score'].apply(lambda x: int(x[:-4])).values

Calling values returns and array from the series(getting rid of the index) 调用值从该系列返回和数组(摆脱索引)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM