我有一個 csv 檔案。如何列印具有特定字串的行后面的行?我需要列印其中包含“ixation”的所有行,然后列印該行后面的行。
這是我當前的代碼
df = pd.read_csv('locationof.csv')
df = pd.DataFrame(data, columns = ['Trial', 'Code','Time','Duration'])
list1 = ['100_1to3_start','fixation','Fixation','66_1to3_start']
contain_values = df[df['Code'].str.contains('|'.join(list1), na=False)]
這是我當前的輸出...
2 1.0 fixation_dummy 50637.0 25086.0
4 2.0 fixation_dummy 75889.0 25086.0
7 3.0 fixation_dummy 101141.0 25086.0
9 4.0 fixation_dummy 126393.0 25086.0
13 6.0 100_1to3_start_2034_1_0_1060 151811.0 20268.0
23 9.0 100_1to3_start_2456_4_0_2054 216104.0 24587.0
33 12.0 100_1to3_start_1507_7_0_2446 283885.0 15118.0
43 15.0 Fixation 332229.0 130081.0
55 17.0 66_1to3_start_2369_2_0_2352 484904.0 23590.0
76 23.0 66_1to3_start_1539_8_0_2518 615150.0 15285.0
82 25.0 Fixation 654357.0 130081.0
123 35.0 Fixation 996089.0 130081.0
164 45.0 Fixation 1343635.0 130081.0
174 46.0 66_1to3_start_1884_1_0_2537 1473882.0 18773.0
197 53.0 66_1to3_start_1541_8_0_2545 1621074.0 15284.0
204 55.0 Fixation 1662939.0 130080.0
213 56.0 100_1to3_start_2115_1_0_2528 1793186.0 21098.0
223 59.0 100_1to3_start_1892_4_0_2544 1859638.0 18939.0
233 62.0 100_1to3_start_2315_7_0_2537 1918282.0 23259.0
但我想要...
2 1.0 fixation_dummy 50637.0 25086.0
4 2.0 fixation_dummy 75889.0 25086.0
7 3.0 fixation_dummy 101141.0 25086.0
9 4.0 fixation_dummy 126393.0 25086.0
13 6.0 100_1to3_start_2034_1_0_1060 151811.0 20268.0
43 15.0 Fixation 332229.0 130081.0
55 17.0 66_1to3_start_2369_2_0_2352 484904.0 23590.0
82 25.0 Fixation 654357.0 130081.0
123 35.0 Fixation 996089.0 130081.0
164 45.0 Fixation 1343635.0 130081.0
174 46.0 66_1to3_start_1884_1_0_2537 1473882.0 18773.0
204 55.0 Fixation 1662939.0 130080.0
213 56.0 100_1to3_start_2115_1_0_2528 1793186.0 21098.0
我如何只列印出僅在一行中帶有“ixation”的行 66_1to3..、100_1to3...)?此代碼將在一系列 csv 檔案上運行,其中我需要的確切行因 csv 檔案而異。
uj5u.com熱心網友回復:
要回答此描述:“我需要列印其中包含“ixation”的所有行,然后是該行之后的行。 ”,解決方案是:
# identify rows with "ixation"
mask = df['Code'].str.contains('ixation')
# select them and one row below
out = df[mask|mask.shift()]
uj5u.com熱心網友回復:
嘗試使用布爾索引,shift因為我們只關心“ixation”之后的行
list1 = ['100_1to3_start', '66_1to3_start']
df[df[2].str.contains('|'.join(list1), na=False) & df[2].shift().str.contains('ixation')]
0 1 2 3 4
4 13 6.0 100_1to3_start_2034_1_0_1060 151811.0 20268.0
8 55 17.0 66_1to3_start_2369_2_0_2352 484904.0 23590.0
13 174 46.0 66_1to3_start_1884_1_0_2537 1473882.0 18773.0
16 213 56.0 100_1to3_start_2115_1_0_2528 1793186.0 21098.0
請注意df[2],根據您的示例,將是df['Code']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464366.html
上一篇:將公式應用于熊貓資料框
下一篇:如何按值索引,分組
