Home > database >  Extract strings values from DataFrame column
Extract strings values from DataFrame column

Time:08-31

I have the following DataFrame:

Student food
1 R0100000
2 R0200000
3 R0300000
4 R0400000

I need to extract as a string the values of the "food" column of the df DataFrame when I filter the data.

For example, when I filter by the Student=1, I need the return value of "R0100000" as a string value, without any other characters or spaces.

This is the code to create the same DataFrame as mine:

    data={'Student':[1,2,3,4],'food':['R0100000', 'R0200000', 'R0300000', 'R0400000']}
    df=pd.DataFrame(data)

I tried to select the Dataframe Column and apply str(), but it does not return me the desired results:

    df_new=df.loc[df['Student'] == 1]
    df_new=df_new.food
    df_str=str(df_new)

    del df_new

CodePudding user response:

This works for me:

s = df[df.Student==1]['food'][0]

s.strip()

CodePudding user response:

It's pretty simple, first get the column. like, col =data["food"] and then use col[index] to get respective value So, you answer would be data["food"][0] Also, you can use iloc and loc search for these. (df.iloc[rows,columns], so we can use this property to get answer as, df.iloc[0,1]) df.loc[rows, column_names] example: df.loc[0,"food"]

  • Related