python - 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)
解决方案
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
推荐阅读
- linux - ElasticSearch 7.2.0 - 节点在集群模式下不相互连接
- javascript - 如何使用用户输入表单的数据创建弹出窗口?
- javascript - 自动将图像网格向左对齐
- c++ - 如何使 C++ 软件中的代码与 arduino 板通信?
- python - Python:从子返回“无”并打印返回值
- javascript - 在鼠标悬停时播放声音和移动图像
- bash - 如何使用 shell 脚本中的 sed 替换 txt 文件中某行中特定字符串之后的字符串?
- bash - 是否有一个 Bash 函数允许我在它们具有相同的第一个单词时从文件中分离/删除/隔离行
- r - 如何根据另一列的变化创建二进制变量?
- java - 如何使用 XPath 通过另一个属性的值过滤元素?