python - 可能是基本的,但打印 pandas 变量的实际名称,而不是数据框本身

标签 python pandas

感觉这是一个非常简单的问题,但我的大脑已经崩溃了。

如果我有几个包含 pandas 系列的变量,当我尝试打印时,如何引用变量名称本身而不是内容。这就是发生的事情。

first = pd.Series({1:2, 2:4})
second = pd.Series({1:5, 2:7})
all = [first, second]

for i in all:
    print i, 'has a sum of', i.sum()

当前打印每个变量的整个数据帧。我如何最终得到如下输出:

“第一个的总和为 6

第二个的总和为 12"

最佳答案

我个人会使用字典:

In [15]:
first = pd.Series({1:2, 2:4})
second = pd.Series({1:5, 2:7})
d={}
d['first']=first
d['second']=second
​
for k,v in d.items():
    print(k, 'has a sum of', v.sum())

输出:

first has a sum of 6
second has a sum of 12

也不要使用变量名称 all 这会影响函数 all

编辑

如果顺序很重要,那么您可以使用 OrderedDict:

In [20]:

from collections import OrderedDict
first = pd.Series({1:2, 2:4})
second = pd.Series({1:5, 2:7})
d=OrderedDict()
d['first']=first
d['second']=second
​
for k,v in d.items():
    print(k, 'has a sum of', v.sum())
first has a sum of 6
second has a sum of 12

关于python - 可能是基本的,但打印 pandas 变量的实际名称,而不是数据框本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30674777/

相关文章:

python - 使用 Python Flask 上传 CSV 文件并进行处理

python - 使用 numpy.max/numpy.min 作为时间戳值

python - 用 pandas 计算比率

python - 如何将 `style` 与 DataFrame 上的 `to_html` 类结合使用?

python - 'using a dict on a Series for aggregation' 的替代方案是什么

python - 如何使用 pandas 查找大写或小写的单词?

python - 将列表列表替换为 "condensed"列表列表,同时保持顺序

python - 如何编写多行Python字符串: triple quotes vs the parenthesis "trick"

python - 使用 SqlAlchemy 在无限循环中获取新结果

python - 从 HTML 返回 png