Favorable way of referencing a filtered data frame column

I have a Dataframe that looks like this:

>>>df
      Source              Log  Size
0        USB         file.txt   256
1  Bluetooth         song.wav    75
2        USB  spreadsheet.xls   129

I want to splicate based on a column Source, and then select only the column Log. The following code works, but I don’t think this is a way to write it, because I read that it is wrong to use inverse brackets ][.

df[df['Source'] == 'USB']['Log']

Is there a better way to do this?

+4
source share
3 answers

Probably the most convenient way is to use . loc with boolean indexing.

You can use .loc:

df.loc[df['Source'] =="USB",'Log']

Conclusion:

0           file.txt
2    spreadsheet.xls
Name: Log, dtype: object

Or more readable syntax with . query .

You can use query:

df.query('Source == "USB"')['Log']

Conclusion:

0           file.txt
2    spreadsheet.xls
Name: Log, dtype: object
+2

][ , , , NumPy Pandas. ( ), ( ) .

[df['Source'] == 'USB'] , ['Log'] .

: .

0

One of the methods -

df.Log[df['Source'] == 'USB']

He will return

0           file.txt
2    spreadsheet.xls
0
source

Source: https://habr.com/ru/post/1678831/


All Articles