简体   繁体   中英

Python 3.6: Find first occurance string(entire column value) from dataframe which starts with '$'

I have dataframe with 55 columns, want to find first occurance string where column value satrts with '$'

I tried below script, but could not achieve.

string = ''
for col in df:
    string=df[col].str.startswith('$')
    if string!='': sys.exit()

sample df:

Col1    Col2    Col3    Col4
123 5678    $45678  $5000
54356   768 Rs.5432 6546

Expected result: $45678, which is present in 3rd column

You can create mask first:

m = df.astype(str).applymap(lambda x: x.startswith('$'))
print (m)
    Col1   Col2   Col3   Col4
0  False  False   True   True
1  False  False  False  False

And then get position of first True in rows and columns by numpy.where for select by iat :

print (np.where(m))
(array([0, 0], dtype=int64), array([2, 3], dtype=int64))

idx = np.where(m)[0][0]
col = np.where(m)[1][0]

a = df.iat[idx, col]
$45678

Use numpy.char.startswith :

for col in df:
    if np.any(np.char.startswith(np.asarray(df[col], str), '$')):
        string = col
        break
else:
    sys.exit()

IIUC you can use .loc and .iloc based on condition ie

mask = df.apply(lambda x : x.str.startswith('$').any(),0)
#mask will return the boolean values so using loc we can access the columns
col = df.loc[:,mask].iloc[:,0]

Output col :

0     $45678
1    Rs.5432
Name: Col3, dtype: object
col[col.str.startswith('$')].values[0]

'$45678'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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