0

I'm iterating over a dataframe, and I'm looking to retrieve the column names of every single row that has cells matching a certain value. For example, let's say row 1 has 100 columns. From those 100 columns, 30 contain the value I'm looking for. I want the names of the all columns that contained that value. Here is what I've done so far:

for _, temp in df.iterrows():
    print(temp[(temp == 1.0)])

Here's a sample output of the previous print statement, where 1.0 is the value I'm interested in.

Product 1      1.0
Product 2      1.0
Product 3      1.0
Product 4      1.0
Product 5      1.0
Name: 1, dtype: float64

The problem that I'm facing is that I am unable to store those names in a list. I've tried:

for _, temp in df.iterrows():
    temp_1 = temp[(temp == 1.0)]
    print(temp_1.columns.values)

but I get AttributeError: 'Series' object has no attribute 'columns'

Please help. Thanks in advance!

Sam
  • 641
  • 1
  • 7
  • 17
  • your code says "columns.values", your error says "columns_values". – cs95 Feb 04 '19 at 18:59
  • oops typo, it's AttributeError: 'Series' object has no attribute 'columns' – Sam Feb 04 '19 at 19:00
  • Can you instead print `df.head()` and show your expected output? There's no need to iterate over DataFrames if you don't have to. – cs95 Feb 04 '19 at 19:02
  • I need to iterate through every row because the output will vary from row to row. My expected output is like the sample above, it's just that sometimes you'll have more or less products. Would you know how to retrieve their names? – Sam Feb 04 '19 at 19:20
  • Maybe temp_1.index.tolist() – cs95 Feb 04 '19 at 19:30
  • Blessed, it worked! – Sam Feb 04 '19 at 19:32
  • Great. That means this is a duplicate of this post: https://stackoverflow.com/a/54324513/4909087 please consider reading and upvoting if it was helpful. – cs95 Feb 04 '19 at 19:33

0 Answers0