簡體   English   中英

如何基於熊貓python中的另一個數據框獲取數據框的子集

[英]How to get the subset of dataframe based on another dataframe in pandas python

我剛剛學習了熊貓,基本上我想根據存儲在另一個數據框中的ID獲取數據框中的某些行。 讓我向您展示代碼:

import pandas as pd
from sklearn.model_selection import train_test_split

f_data="data.tsv"
all_data = pd.read_csv(f_data,delimiter='\t',encoding='utf-8',header=None)
x_data = all_data[[0,1,3]]
y_data = all_data[[2]]

# Split train and test sets
x_train,x_test,y_train,y_test = train_test_split(x_data,y_data,test_size=0.1)

all_data共有12列。 我在x_data中使用3列,在y_data中使用1列。

一旦創建了x_trainx_test ,我想將這些實例寫入tsv文件,但是在執行此操作時,我想寫入存儲在all_data所有12列。 為此,我需要將x_trainx_test中的實例與x_test進行all_data 我該怎么辦?

編輯

我的數據如下所示:

all_data

        0                                                  1                              2    3   ...                                                8                      9     10    11
0       35  Auch in Großbritannien, wo 19 Atomreaktoren in...                       Ausstieg -1.0  ...                                      Sunday Times           Sunday Times   NaN     1

# continues like that

x_train

         0                                                  1    3
939   2074  Die CSU verlangt von der schwarz-gelben Koalit...  1.0

因此,我想做的是在all_data中獲取以939,710,288,854,433開頭的行,並將其寫入文件。

拆分數據的index與原始數據相對應,可用於查找原始數據(假設索引是唯一的):

all_data.loc[x_train.index]
all_data.loc[x_test.index]

暫無
暫無

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

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