![](/img/trans.png)
[英]Python Pandas: checking value of one column into column of another dataframe
[英]Checking one column and returning another column, in a Pandas Dataframe
我有一個這樣的數據框:
Title Participants
0 ShowA B. Smith,C. Ball
1 ShowB T. Smooth
2 ShowC K. Dulls,L. Allen,B. Smith
我在,
在參與者列中拆分並為每個單元格創建一個列表。 接下來,我檢查每個列表中的特定參與者。 在這個例子中,我正在檢查B. Smith
或K. Dulls
for item in df['Participants']:
listX = item.split(',')
if 'B. Smith' in listX or 'K. Dulls' in listX:
print(listX)
這將返回:
['B. Smith', 'C. Ball']
['K. Dulls', 'L. Allen', 'B. Smith']
1)我猜在我的if
語句中有一種更簡潔的方法來檢查多個參與者。 我喜歡任何建議。
2)這是我一直在轉圈的地方,我如何返回與我返回的列表相關的Title
?
在這個例子中,我想返回:
ShowA
ShowC
設置代碼:
import pandas as pd
df = pd.DataFrame(data={'Title': ['ShowA', 'ShowB', 'ShowC'],
'Participants': ['B. Smith,C. Ball', 'T. Smooth', 'K. Dulls,L. Allen,B. Smith']})
target_participants = ['B. Smith', 'K. Dulls']
get_dummies
您可以使用pandas.Series.str.get_dummies
並創建一個數據pandas.Series.str.get_dummies
,其中列是名稱所在位置的布爾表達式。
dummies = df.Participants.str.get_dummies(',').astype(bool)
dummies
B. Smith C. Ball K. Dulls L. Allen T. Smooth
0 True True False False False
1 False False False False True
2 True False True True False
然后我們可以找到你的結果
df.loc[dummies['B. Smith'] | dummies['K. Dulls'], 'Title']
0 ShowA
2 ShowC
Name: Title, dtype: object
contains
否則,您可以使用pandas.Series.str.contains
。 首先,我們需要在列表中指定您要查找的人員,然后構造一個字符串以用作正則表達式。
people_to_look_for = ['B. Smith', 'K. Dulls']
pattern = '|'.join(people_to_look_for)
mask = df.Participants.str.contains(pattern)
df.loc[mask, 'Title']
0 ShowA
2 ShowC
Name: Title, dtype: object
我不確定這樣做的性能會有多好,但我認為如果您將'Participants'
列的元素保留為列表,那么投資是值得的。
import pandas as pd
df = pd.DataFrame(data={'Title': ['ShowA', 'ShowB', 'ShowC'],
'Participants': ['B. Smith,C. Ball', 'T. Smooth', 'K. Dulls,L. Allen,B. Smith']})
target_participants = {'B. Smith', 'K. Dulls'}
df['Participants'] = df['Participants'].str.split(',')
print(df, end='\n\n')
contains_parts = ~df['Participants'].map(target_participants.isdisjoint)
print(contains_parts)
輸出:
Title Participants
0 ShowA [B. Smith, C. Ball]
1 ShowB [T. Smooth]
2 ShowC [K. Dulls, L. Allen, B. Smith]
0 True
1 False
2 True
Name: Participants, dtype: bool
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.