简体   繁体   English

根据条件从原始数据框中提取行以创建新数据框

[英]Extracting rows from original data frame based on condition to create new data frame

Given a data frame, I am interested in extracting rows with IDs that match IDs in a given list and turning these rows into a new data frame.给定一个数据框,我有兴趣提取具有与给定列表中的 ID 匹配的 ID 的行,并将这些行转换为一个新的数据框。

Example:例子:

ids_list=[123, 345, 567, 789, 234, 456, 678] ids_list=[123, 345, 567, 789, 234, 456, 678]

oringal_df oringal_df

ids身份证 grade年级 major重大的
123 123 98 98 Engineering工程
345 345 100 100 English英语
111 111 64 64 History历史
456 456 85 85 Drama戏剧
444 444 75 75 Math数学

new_df is created with rows where oringal_df[ids] is in ids_list new_df 是使用 oringal_df[ids] 在 ids_list 中的行创建的

ids身份证 grade年级 major重大的
123 123 98 98 Engineering工程
345 345 100 100 English英语
456 456 85 85 Drama戏剧

I wrote the following and I have tried other variations but I keep getting errors.我写了以下内容,并尝试了其他变体,但我不断收到错误。 Please help.请帮忙。

for i in original_df.loc[original_df['ids']]:
    if original_df[i].isin(ids_list):
        data=original_df.loc[original_df[i]]
        new_df=pd.DataFrame(data)

This is better:这个更好:

new_df = df.loc[df['ids'].isin(ids_list)]
print(new_df)

output: output:

   ids  grade        major
0  123     98  Engineering
1  345    100      English
3  456     85        Drama

using merge should do what you want:使用合并应该做你想做的事:

ids_list=[123, 345, 567, 789, 234, 456, 678]
id_df = pd.DataFrame(ids_list , columns = ["sid"])
mergedf = pd.merge(original_df , id_df , on = 'sid)

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

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