根据条件提取行 Pandas Python [英] Extract rows based on conditions Pandas Python
本文介绍了根据条件提取行 Pandas Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果应用了某些条件,我需要提取行.
- 列
col1
应包含列表list_words
中的所有单词. - 最后一个词应该是
Story
- 下一行的最后一个单词应该是 b
ac
:
这是我当前的代码:
将pandas导入为pddf = pd.DataFrame({'col1': ['Sraft SW Quality Assurance Story', 'alex ac', 'anny ac', 'antoine ac','azeepic', 'bella ac', 'Complete SW Quality Assurance计划故事'、'celine ac'、'wqas 史诗'、'karmen ac'、'kameilia ac'、'更新 SW 质量保证计划故事'、'约瑟夫 ac'、'更新 SW 质量保证计划 ac'、'约瑟夫 ac''],'col2': ['aa', 'bb', 'cc', 'dd','ee', 'ff', 'gg', 'hh', 'ii', 'jj', 'kk', 'll', 'mm', 'nn', 'oo']})打印(df)list_words="软件质量计划故事"set_words = set(list_words.split())#检查list_words是否在单元格中df['TrueFalse']=pd.concat([df.col1.str.contains(word,regex=False) for word in list_words.split()],axis=1).sum(1) >1打印('\n',df)#提取最后一个词df["后缀"] = df["col1"].str.split().str[-1]打印('\n',df)df['ok']=''对于范围内的 i (len(df)-1):if ((df["Suffix"].iloc[i]=='Story') & (df["TrueFalse"].iloc[i]=='True') & (df["Suffix"].iloc[i+1]=='ac')):df['ok'].iloc[i+1]=df["后缀"].iloc[i+1]打印('\n',df)
输出:
col1 col2 TrueFalse 后缀ok0 草案 SW 质量保证故事 aa 真实故事1 亚历克斯 ac bb 假 ac2 anny ac cc 假 ac3 antoine ac dd 假 ac4 aze 史诗 ee 假史诗5 bella ac ff 假 ac6 完整的软件质量保证计划故事 gg 真实故事7 celine ac hh 假ac8 wqas 史诗 ii 假史诗9 karmen ac jj 假 ac10 卡梅利亚 ac kk 假 ac11 更新 SW 质量保证计划故事 ll 真实故事12 joseph ac mm 假 ac13 更新软件质量保证计划 ac nn True ac14 约瑟夫 ac oo 假 ac
line 13 应该设置为 False
所需的输出:
col1 col2 TrueFalse 后缀1 完整的软件质量保证计划故事 gg 真实故事2 celine ac hh 真 ac3 更新 SW 质量保证计划故事 ll 真实故事4 joseph ac mm 真交流
解决方案
这里是所有不同的条件,以及它们的交集:
# 条件1:col1中的所有单词减去set_words中的所有单词必须为空df["condition_1"] = df.col1.apply(lambda x: not bool(set_words - set(x.split())))# 条件2:最后一个词应该是'Story'df["condition_2"] = df.col1.str.endswith("故事")# 条件 3:下一行的最后一个单词应该是 ac.参见`shift(-1)`df["condition_3"] = df.col1.str.endswith("ac").shift(-1)# 当所有三个条件都满足时:新列 'conditions'df["条件"] = df.condition_1 &df.condition_2 &df.condition_3# 回到你的符号:# TrueFalse:满足所有三个条件的行及其下一行df["TrueFalse"] = df.conditions |df.conditions.shift(1)df["后缀"] = df.col1.apply(lambda x: x.split()[-1])
现在你想要的输出:
<预><代码>>>>打印(df[[col1",col2",真假",后缀"]][df.真假])col1 col2 TrueFalse 后缀6 完整的软件质量保证计划故事 gg 真实故事7 celine ac hh 真 ac11 更新 SW 质量保证计划故事 ll 真实故事12 joseph ac mm 真交流仅供参考,所有数据框:
<预><代码>>>>打印(df[[col1",col2",真假",后缀"]])col1 col2 TrueFalse 后缀0 草案 SW 质量保证故事 aa 虚假故事1 亚历克斯 ac bb 假 ac2 anny ac cc 假 ac3 antoine ac dd 假 ac4 aze 史诗 ee 假史诗5 bella ac ff 假 ac6 完整的软件质量保证计划故事 gg 真实故事7 celine ac hh 真 ac8 wqas 史诗 ii 假史诗9 karmen ac jj 假 ac10 卡梅利亚 ac kk 假 ac11 更新 SW 质量保证计划故事 ll 真实故事12 joseph ac mm 真交流13 更新软件质量保证计划 ac nn False ac14 约瑟夫 ac oo 假 acI need to extract rows if certain conditions are applied.
- the column
col1
should contain all the words in the listlist_words
. - the last word should be
Story
- the last word in the next row should b
ac
:
This is my current code:
import pandas as pd
df = pd.DataFrame({'col1': ['Draft SW Quality Assurance Story', 'alex ac', 'anny ac', 'antoine ac','aze epic', 'bella ac', 'Complete SW Quality Assurance Plan Story', 'celine ac','wqas epic', 'karmen ac', 'kameilia ac', 'Update SW Quality Assurance Plan Story', 'joseph ac','Update SW Quality Assurance Plan ac', 'joseph ac'],
'col2': ['aa', 'bb', 'cc', 'dd','ee', 'ff', 'gg', 'hh', 'ii', 'jj', 'kk', 'll', 'mm', 'nn', 'oo']})
print(df)
list_words="SW Quality Plan Story"
set_words = set(list_words.split())
#check if list_words is in the cell
df['TrueFalse']=pd.concat([df.col1.str.contains(word,regex=False) for word in list_words.split()],axis=1).sum(1) > 1
print('\n',df)
#extract last word
df["Suffix"] = df["col1"].str.split().str[-1]
print('\n',df)
df['ok']=''
for i in range (len(df)-1):
if ((df["Suffix"].iloc[i]=='Story') & (df["TrueFalse"].iloc[i]=='True') & (df["Suffix"].iloc[i+1]=='ac')):
df['ok'].iloc[i+1]=df["Suffix"].iloc[i+1]
print('\n',df)
output:
col1 col2 TrueFalse Suffix ok
0 Draft SW Quality Assurance Story aa True Story
1 alex ac bb False ac
2 anny ac cc False ac
3 antoine ac dd False ac
4 aze epic ee False epic
5 bella ac ff False ac
6 Complete SW Quality Assurance Plan Story gg True Story
7 celine ac hh False ac
8 wqas epic ii False epic
9 karmen ac jj False ac
10 kameilia ac kk False ac
11 Update SW Quality Assurance Plan Story ll True Story
12 joseph ac mm False ac
13 Update SW Quality Assurance Plan ac nn True ac
14 joseph ac oo False ac
line 13 should be set to False
desired output :
col1 col2 TrueFalse Suffix
1 Complete SW Quality Assurance Plan Story gg True Story
2 celine ac hh True ac
3 Update SW Quality Assurance Plan Story ll True Story
4 joseph ac mm True ac
解决方案
Here are your all different conditions, and their intersection:
# Condition 1: all words in col1 minus all words in set_words must be empty
df["condition_1"] = df.col1.apply(lambda x: not bool(set_words - set(x.split())))
# Condition 2: the last word should be 'Story'
df["condition_2"] = df.col1.str.endswith("Story")
# Condition 3: the last word in the next row should be ac. See `shift(-1)`
df["condition_3"] = df.col1.str.endswith("ac").shift(-1)
# When all three conditions meet: new column 'conditions'
df["conditions"] = df.condition_1 & df.condition_2 & df.condition_3
# Back to your notation:
# TrueFalse: rows that fulfill all three conditions along with their next rows
df["TrueFalse"] = df.conditions | df.conditions.shift(1)
df["Suffix"] = df.col1.apply(lambda x: x.split()[-1])
Now your desired output:
>>> print(df[["col1", "col2", "TrueFalse", "Suffix"]][df.TrueFalse])
col1 col2 TrueFalse Suffix
6 Complete SW Quality Assurance Plan Story gg True Story
7 celine ac hh True ac
11 Update SW Quality Assurance Plan Story ll True Story
12 joseph ac mm True ac
FYI, all the dataframe:
>>> print(df[["col1", "col2", "TrueFalse", "Suffix"]])
col1 col2 TrueFalse Suffix
0 Draft SW Quality Assurance Story aa False Story
1 alex ac bb False ac
2 anny ac cc False ac
3 antoine ac dd False ac
4 aze epic ee False epic
5 bella ac ff False ac
6 Complete SW Quality Assurance Plan Story gg True Story
7 celine ac hh True ac
8 wqas epic ii False epic
9 karmen ac jj False ac
10 kameilia ac kk False ac
11 Update SW Quality Assurance Plan Story ll True Story
12 joseph ac mm True ac
13 Update SW Quality Assurance Plan ac nn False ac
14 joseph ac oo False ac
这篇关于根据条件提取行 Pandas Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文