【问题标题】:Appropriate Time to Dynamically Set Variable Names?动态设置变量名的合适时机?
【发布时间】:2016-09-21 20:55:46
【问题描述】:

编辑:原来答案是明确的“不”。但是,我仍在努力用正确数量的条目填充列表。


我一直在搜索 StackOverflow,我一直发现动态设置变量名不是一个好的解决方案。但是,我想不出另一种方法来解决这个问题。

我有一个从pandas 创建的DataFrame(从 excel 中读取),其中包含带有字符串标题和整数条目的列,以及一列具有从 1 到 52 顺序增加的数字(我们称之为周)。我想要做的是创建单独的列表,每个列表都以列标题命名,条目是出现列出整数次数的周数。

这对于几列来说很简单,只需手动创建列表名称,但随着列数的增加,这可能会有点失控。

残酷的解释,这是我能想到的最好的解释。希望一个简化的例子可以澄清。

week  str1    str2    str3   
1       8       2        5        
2       1       0        3    
3       2       1        1 

期望的输出:

str1_count = [1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3] # eight 1's, one 2, and two 3's
str2_count = [1, 1, 3]                         # two 1's, one 3
str3_count = [1, 1, 1, 1, 1, 2, 2, 2, 3]       # five 1's, three 2's, one 3

到目前为止我所拥有的:

results = {}
df = pd.DataFrame(from_csv(...., sep = ","))
for key in df:
    for i in df[key]
        results[key] = i # this only creates a list with the int value of the most recent i

【问题讨论】:

  • 为什么它们需要是变量?为什么不能使用以名称为键的字典呢?
  • 使用字典。
  • 是的,为什么不用字典
  • 我认为字典是由许多独特的key:value 对构成的。我需要将大量值存储在一个列表中(最终为每个列表创建一个单独的 excel 文件)......还是我误解了字典的工作原理?我可以有{str1: 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3} 吗?或{str1: [1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3]}。如果是这样,我将如何设置?
  • 值可以是一个列表。

标签: python pandas dataframe


【解决方案1】:

那么,像这样吗?

import collections
import csv
import io

reader = csv.DictReader(io.StringIO('''
week,str1,str2,str3
1,8,2,5
2,1,0,3
3,2,1,1
'''.strip()))

data = collections.defaultdict(list)
for row in reader:
    for key in ('str1', 'str2', 'str3'):
        data[key].extend([row['week']]*int(row[key]))

from pprint import pprint
pprint(dict(data))

# Output:
{'str1': ['1', '1', '1', '1', '1', '1', '1', '1', '2', '3', '3'],
 'str2': ['1', '1', '3'],
 'str3': ['1', '1', '1', '1', '1', '2', '2', '2', '3']}

注意:Pandas 非常适合处理数据并对其进行一些有趣的操作,但如果您只需要一些简单的东西,则不需要它。这是其中一种情况。

【讨论】:

  • 谢谢!我只是使用 Pandas 从 Excel 中读取数据,但从现在开始我将使用 csv 模块来做一些简单的事情。
  • 你可以read them without using pandas,不过如果你有 Pandas,用它来读取你的 excel 文件并没有什么问题,我敢肯定。
猜你喜欢
  • 2019-12-23
  • 2019-01-29
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
  • 2020-06-22
相关资源
最近更新 更多