首页 > 解决方案 > unpack dataframe column and return rows based on certain word

问题描述

Maybe a noob question but from the dataframe below I cannot figure out how to unpack column B of the following to then just show the rows with 'close' price.

It looks as though column B data is a dictionary that needs unpacking and then somehow filtered so only the rows with a 'close' value show, which can be an integer or string

import pandas as pd


df = pd.DataFrame(

{
"A": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "tsla",
    "3. Last Refreshed": "2020-01-27",
    "4. Output Size": "Full size",
    "5. Time Zone": "US/Eastern"
},
"B": {

    "2019-09-26": {
        "1. open": "230.6600",
        "2. high": "243.3100",
        "3. low": "227.4000",
        "4. close": "242.5600",
        "5. volume": "12078785"
    },
    "2019-09-25": {
        "1. open": "224.5600",
        "2. high": "228.9800",
        "3. low": "218.3600",
        "4. close": "228.7000",
        "5. volume": "9444286"
    },
    "2019-09-24": {
        "1. open": "241.5200",
        "2. high": "241.9900",
        "3. low": "222.6100",
        "4. close": "223.2100",
        "5. volume": "12941112"
    },
    "2019-09-23": {
        "1. open": "240.0000",
        "2. high": "245.1794",
        "3. low": "239.2200",
        "4. close": "241.2300",
        "5. volume": "4391630"
   }
}
}
)
print(df)

The following is what I am trying to achieve from data above:

import pandas as pd

df = pd.DataFrame()

df['A'] = '2019-09-26','2019-09-25','2019-09-24','2019-09-23'

df['B'] = 242.5600,228.7000,223.2100,241.2300

print(df)

标签: pythonpandasnumpydataframe

解决方案


You could unpack that, or you could simply use yfinance.

import pandas as pd
import yfinance as yf
yf.download("tsla", start='2019-09-20')

Returning a dataframe.

              Open    High     Low   Close  Adj Close    Volume
Date                                                           
2019-09-20  246.49  246.95  238.16  240.62     240.62   6353000
2019-09-23  240.00  245.18  239.22  241.23     241.23   4340200
2019-09-24  241.52  241.99  222.61  223.21     223.21  12891500
2019-09-25  224.56  228.98  218.36  228.70     228.70   9427100
2019-09-26  230.66  243.31  227.40  242.56     242.56  11884500
2019-09-27  242.20  248.71  238.73  242.13     242.13  11116400

推荐阅读