python - pandas 列值和变量值字符串连接

标签 python python-3.x pandas

我有以下代码

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())

关于python - pandas 列值和变量值字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59689005/

相关文章:

python - 错误 R10(启动超时)-> Web 进程在启动后 60 秒内无法绑定(bind)到 $PORT

python - 从 csv 文件创建元组列表

python - 使用多线程(使用并发.futures)在Python中添加列表会导致偏移行

python - 在 Pandas 中使用 groupby 时恢复分层列索引

python - 将列从一个数据帧映射到另一个数据帧以创建新列

pandas - 使用 Pandas 按日期计数值的频率

python - 如何在 Tkinter 网格中左对齐标签和输入框

python - "if"语句查找剩余数字并附加到 csv 列表中

python - 使用 python 代码没有在 mapreduce 中获得预期的输出

python - 从 python 程序中禁用哈希随机化