【问题标题】:Python recognise with and without quotation marksPython识别带引号和不带引号
【发布时间】:2020-07-29 06:04:25
【问题描述】:

我有这行代码可以工作。

price = df1.loc[:, ['price', 'date']]

我需要将其模拟为与销售和收入等其他指标的循环。这可能吗?即如何让 Python 引用列表中带引号和不带引号的单词?

listx = [price,sales, revenue]
for a in listx:
    a = df1.loc[:, ['a', 'date']]

【问题讨论】:

  • 您可以在问题中添加示例数据和预期输出吗?
  • listx 是变量列表还是字符串列表?
  • Python 在定义列表时不知道价格、销售额和收入是多少。但最终目标是让它看起来像我在上面定义的价格。

标签: python python-3.x pandas list dataframe


【解决方案1】:

IIUC,你可以做这样的事情,使用列表理解:

listx = ['price','sales', 'revenue']
price, sales, revenue=[df1.loc[:, [a, 'date']] for a in listx]

一般来说,这可能是一种使用globals的方法:

listx = ['price','sales', 'revenue']
for a in listx:
    globals().update({a:df1.loc[:, [a, 'date']]})

根据 cmets 的要求,以后请提供minimal reproducible example

【讨论】:

  • 有没有办法做第二行而不必列出它们而不用引号?也许以更一般的方式?
  • 我得到:“KeyError: 'Passing list-likes to .loc or [] with any missing labels,”
  • df1 的列中似乎没有至少一个标签。 df1 中的所有列名都存在?也许通过数据框的样本,我们也许可以找到错误的原因。 @arv
  • 我想我已经找到原因了。抱歉,有没有办法设置索引,并使用这种方法将 na 放在同一行中?喜欢price = df1.loc[:, ['price', 'date']].set_index('date').dropna(how='all')
  • 是的,你回答了你自己的问题,这就是@arv
【解决方案2】:

一种方法是将其保存在字典中:

metrics = {}
listx = ['price', 'sales', 'revenue']
for a in listx:
    metrics[a] = df1.loc[:, [a, 'date']]

现在您可以使用 metric['sales'] 等访问指标。


也许我误解了你的问题。以后请提供minimal reproducible example

【讨论】:

  • 我得到:“KeyError: '不再支持将列表喜欢传递给 .loc 或 [] 并带有任何缺失的标签。”
  • 列表中的一个元素不在列中。有关更多信息,请参阅official documentation。检查列表元素的拼写。
猜你喜欢
  • 2021-09-18
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2019-10-11
  • 2012-05-05
相关资源
最近更新 更多