python - pandas 列值和变量值字符串 concat
问题描述
我有以下代码
import requests
import json
import pandas as pd
from datetime import datetime
from datetime import timedelta
pd.options.display.float_format = '{:,.2f}'.format
url="https://nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O"
headers = { "Accept-Encoding":"gzip, deflate","Accept-Language":"en-US,en;q=0.9",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 OPR/65.0.3467.78"}
r=requests.get(url, headers=headers).json()
df1=pd.DataFrame().from_records(r['data'])
df2=df1[['symbol','dayHigh','dayLow','lastPrice','yearHigh','yearLow','previousClose','change','pChange']]
df2=df2.sort_values(['symbol'], ascending=True).reset_index(drop=True)
nifty1=df2.round(2)
nifty1
dt1 = '01-01-2020'
dt2 = '11-01-2020'
生成以下输出
symbol dayHigh dayLow lastPrice yearHigh yearLow previousClose change pChange
0 ACC 1525 1487.25 1510.8 1769.05 1326 1486.15 24.65 1.66
1 ADANIENT 213 205.9 210.5 221.5 113 208 2.50 1.20
2 ADANIPORTS 394.3 390 391.3 430.6 292.1 391.8 -0.50 -0.13
...
我有以下字符串
https://nseindia.com/api/historical/cm/equity?symbol=XXXX&series=["EQ"]&from=fromdt&to=todt
我想用 nifty1['symbol'] 列替换 XXXX,最好没有空格和 fromdt 和 todt 用 dt1 和 dt2
例如。
https://nseindia.com/api/historical/cm/equity?symbol=ACC&series=["EQ"]&from=01-01-2020&to=11-01-2020
https://nseindia.com/api/historical/cm/equity?symbol=ADANIENT&series=["EQ"]&from=01-01-2020&to=11-01-2020
https://nseindia.com/api/historical/cm/equity?symbol=ADANIPORTS&series=["EQ"]&from=01-01-2020&to=11-01-2020
并存储到新的数据框中
解决方案
这是一种使用方法f-strings
:
new_df = (df['symbol']
.apply(lambda x: f'https://nseindia.com/api/historical/cm/equity?symbol={x}&series=["EQ"]&from=fromdt&to=todt')
.to_frame())
推荐阅读
- google-sheets - 是否可以为表单条目使用自定义字体?
- r - 如何根据来自两个不同变量的值生成虚拟处理变量
- assembly - 汇编——为什么在处理局部变量时减去`rsp`而不是push?
- sql - 当订单具有相同数量的项目时如何使用 SUM DISTINCT
- java - Java条件运算符三种可能的结果
- python - 追加到空 np 数组或为数组分配新值
- python - 用python拟合二维数据
- php - 如何在 Prado 3.3.0 中为 MasterClass 编写正确的 application.php 配置?
- python - 具有两个参数的参数化 sql 查询,其中一个是列表的集合
- android - AndroidX Spinner 不显示列表