使用python切片删除数据集列

2024-04-18 12:13:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

dataframe = pd.DataFrame({'Date': ['2017-04-01 00:24:17','2017-04-01 00:54:16','2017-04-01 01:24:17'] * 1000, 'Luminosity':[2,3,4] * 1000})

dataframe的输出如下:

      Date                Luminosity
0   2017-04-01 00:24:17     2
1   2017-04-01 00:54:16     3
2   2017-04-01 01:24:17     4
.           .               . 
.           .               . 

我想删除或只选择Luminosity列,然后,使用python切片,我有以下内容:

X = dataframe.iloc[:, 1].values
# Give a new form of the data
X = X.reshape(-1, 1)

X的输出是以下numpy数组:

array([[2],
   [3],
   [4],
   ...,
   [2],
   [3],
   [4]])

我有同样的情况,但是有一个新的数据帧,有76列,比如this

这是我读它时的输出。你知道吗

enter image description here

总共,dataframe有76列,我只想选择25列,依次命名为PORVL2N1PORVL2N2PORVL4N1等等 直到到达名为PORVL24N2的结束列,这是76th

目前,我的解决方案是只使用我感兴趣的列创建一个新的数据框,这是:

a = df[['PORVL2N1', 'PORVL2N2', 'PORVL4N1', 'PORVL5N1', 'PORVL6N1', 'PORVL7N1', 
    'PORVL9N1', 'PORVL9N1', 'PORVL10N1', 'PORVL13N1', 'PORVL14N1', 'PORVL15N1',
    'PORVL16N1', 'PORVL16N2', 'PORVL18N1', 'PORVL18N2', 'PORVL18N3','PORVL18N4',
    'PORVL21N1', 'PORVL21N2', 'PORVL21N3', 'PORVL21N4', 'PORVL21N5', 'PORVL24N1',
    'PORVL24N2']

输出为:

enter image description here

我想做同样的事情,只选择我感兴趣的列,但是使用python切片和iloc来索引和按位置选择,就像我在问题的开头所做的那样。你知道吗

我知道这是可能的幻灯片,但我不能理解好的切片辛塔克斯得到它。你知道吗

如何使用iloc和切片python来选择我感兴趣的列?你知道吗


Tags: 数据dataframedate切片感兴趣pdvaluesiloc
1条回答
网友
1楼 · 发布于 2024-04-18 12:13:38

考虑到您的数据在dataframedf中,您可以执行以下操作:

cols = list(df.columns)
pos_cols = [ i for i, word in enumerate(cols) if word.startswith('PORVL') ]
df.iloc[:, pos_cols]

或者,可以将.filter()regex一起使用。你知道吗

df.filter(regex=("PORVL.*")) 

有关更多信息,请查看docs。你知道吗

网友
2楼 · 发布于 2024-04-18 12:13:38

使用常规切片表示法。。。你知道吗

>>> df
   a  b  c  d  e
0  1  1  1  1  1
1  2  2  2  2  2
2  3  3  3  3  3
3  4  4  4  4  4
4  5  5  5  5  5
>>> df.iloc[:,2:]
   c  d  e
0  1  1  1
1  2  2  2
2  3  3  3
3  4  4  4
4  5  5  5
>>> df.iloc[:,-2:]
   d  e
0  1  1
1  2  2
2  3  3
3  4  4
4  5  5
>>> 

slice objects也可以

>>> last3 = slice(-3,None)
>>> df.iloc[:,last3]
   c  d  e
0  1  1  1
1  2  2  2
2  3  3  3
3  4  4  4
4  5  5  5
>>>

Selection By Position

相关问题 更多 >