0
import pandas as pd

tweets = pd.read_csv("file_name")

# Group the data by hashtag to extract books with the hashtag RoeVWade only
roevwade = tweets.groupby("hashtags").get_group("['RoeVWade']")

# Print the date of the first tweet with only the RoeVWade hashtag
print(roevwade["created_at"][0])

Drops an error:

KeyError: 0

Fixed this using

roevwade["created_at"].iloc[0]

and got what I needed. However, I need another way without using iloc or iat. It must be a single line like here:

print(roevwade["created_at"][0])

but one that doesn't drop an error. I understand this is a series and not a list, but I have no idea how to print what is needed with a single line of code after assigning roevwade var.

  • It is single line, what do you mean by `roevwade["created_at"].iloc[0]` is not single line. `df['column_name'][index]` should work. What is the type of `roevwade` is it DataFrame or Series? What does `type(roevwade)` returns? – mmustafaicer Aug 03 '22 at 16:33
  • Does this answer your question? [KeyError: 0 when accessing value in pandas series](https://stackoverflow.com/questions/46153647/keyerror-0-when-accessing-value-in-pandas-series) – mmustafaicer Aug 03 '22 at 16:44
  • You can mix position and label based indexing like [this answer](/a/68660630/15497888) `print(df.iloc[0, df.columns.get_loc('created_at')])`, but `print(roevwade["created_at"].iloc[0])` (_e.g._ [this answer](/a/46153757/15497888) and your solution) is probably just fine in most circumstances. – Henry Ecker Aug 04 '22 at 01:28

1 Answers1

0

After "group by" data index will be change, so you must reset index as below

roevwade = tweets.groupby("hashtags").get_group("['RoeVWade']").reset_index(drop=True)
Mr.Bean
  • 65
  • 6