Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

python - Select rows if string begins with certain characters in pandas

I have a csv file as the given picture bellow

enter image description here

I'm trying to find any word that will start with letter A and G or any list that I want

but my code returns an error any Ideas what I'm doing wrong ? this is my code

if len(sys.argv) == 1:
    print("please provide a CSV file to analys")
else:
    fileinput = sys.argv[1]

wdata = pd.read_csv(fileinput)


print( list(filter(startswith("a","g"), wdata)) )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get relevant rows, extract the first letter, then use isin:

df
  words  frequency
0  what         10
1   and          8
2   how          8
3  good          5
4   yes          7

df[df['words'].str[0].isin(['a', 'g'])]
  words  frequency
1   and          8
3  good          5

If you want a specific column, use loc:

df.loc[df['words'].str[0].isin(['a', 'g']), 'words']
1     and
3    good
Name: words, dtype: object

df.loc[df['words'].str[0].isin(['a', 'g']), 'words'].tolist()
# ['and', 'good']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...