簡體   English   中英

從數據框中隨機選擇列

[英]Randomly selecting columns from dataframe

我的問題很簡單:有沒有辦法從Pandas中的數據框中隨機選擇列? 為了清楚起見,我想隨機選出附有值的n 我知道有一種隨機選擇行的方法:

import pandas as pd

df = pd.read_csv(filename, sep=',', nrows=None)
a = df.sample(n = 2)

所以問題是,它是否存在尋找隨機列的等效方法?

sample也接受一個axis參數:

df = pd.DataFrame(np.random.randint(1, 10, (10, 5)), columns=list('abcde'))

df
Out: 
   a  b  c  d  e
0  4  5  9  8  3
1  7  2  2  8  7
2  1  5  7  9  2
3  3  3  5  2  4
4  8  4  9  8  6
5  6  5  7  3  4
6  6  3  6  4  4
7  9  4  7  7  3
8  4  4  8  7  6
9  5  6  7  6  9

df.sample(2, axis=1)
Out: 
   a  d
0  4  8
1  7  8
2  1  9
3  3  2
4  8  8
5  6  3
6  6  4
7  9  7
8  4  7
9  5  6

你可以做df.columns.to_series.sample(n=2)

要隨機對列進行采樣,首先需要通過調用to_series轉換為Series ,然后可以像以前一樣調用sample

In[24]:
df.columns.to_series().sample(2)

Out[24]: 
C    C
A    A
dtype: object

例:

In[30]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df

Out[30]: 
          a         b         c
0 -0.691534  0.889799  1.137438
1 -0.949422  0.799294  1.360521
2  0.974746 -1.231078  0.812712
3  1.043434  0.982587  0.352927
4  0.462011 -0.591438 -0.214508

In[31]:
df[df.columns.to_series().sample(2)]

Out[31]: 
          b         a
0  0.889799 -0.691534
1  0.799294 -0.949422
2 -1.231078  0.974746
3  0.982587  1.043434
4 -0.591438  0.462011

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM