0

I convert json to Pandas dataframe and would like to call the value of "c".

>>> quote
{u'c': 89.77, u'h': 90.51, u'l': 89.32, u'o': 90.09, u'pc': 90.29, u't': 1591778794}
>>> quote = pd.DataFrame(quote.items())
>>> quote
    0             1
0   c  8.977000e+01
1   h  9.051000e+01
2   l  8.932000e+01
3   o  9.009000e+01
4  pc  9.029000e+01
5   t  1.591779e+09

I want the data for c. I currently used quote.iloc[0][1] but it is not robust. What is the robust and elegant way to get the data for "c"?

3
  • quote[quote['0'] == 'c'] should probably work. This way you can get the sub-dataframe where the value of column '0' is 'c' (regardless of its position). Commented Jun 10, 2020 at 8:56
  • It is not working as it cause keyerror 0 Commented Jun 10, 2020 at 9:00
  • How about quote[quote[0] == 'c'] ? Commented Jun 10, 2020 at 9:03

1 Answer 1

1

With quote_items and wanted such as

quote_items = {
    u'c': 89.77,
    u'h': 90.51,
    u'l': 89.32,
    u'o': 90.09,
    u'pc': 90.29,
    u't': 1591778794
}.items()

wanted = 'c'

What about simply setting as index the first column, i.e.

>>> df = pd.DataFrame(quote_items).set_index(0)
>>> df.loc[wanted]
1    89.77
Name: c, dtype: float64

Or even dealing with the transpose to make things shorter

>>> df = pd.DataFrame(quote_items).set_index(0).T
>>> df[wanted]  # <=> df.loc[:, wanted]
1    89.77
Name: c, dtype: float64

Otherwise, if you do not want to locate your data, what follows may be enough

>>> df = pd.DataFrame(quote_items)
>>> df[df[0]==wanted]
   0      1
0  c  89.77

less readable IMHO, and not ending with the same type of object (pd.DataFrame instead of pd.Series as previously)


But in the first place: is your input dictionary really representative of the data you have to deal with ? Depending on that, our answers may vary.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.