【问题标题】:How to solve the FunctionError and MapError如何解决 FunctionError 和 MapError
【发布时间】:2019-10-29 23:28:38
【问题描述】:

Python 3.6 pycharm

import prettytable as pt
import numpy as np
import pandas as pd

a=np.random.randn(30,2)
b=a.round(2)
df=pd.DataFrame(b)
df.columns=['data1','data2']
tb = pt.PrettyTable()

def func1(columns):
    def func2(column):
        return tb.add_column(column,df[column])
    return map(func2,columns)

column1=['data1','data2']
print(column1)
print(func1(column1))

我想得到的结果是:

tb.add_column('data1',df['data1'])
tb.add_column('data2',df['data2'])

事实上,结果是:

<map object at 0x000001E527357828>

我在 Stack Overflow 中找了很久,有的回答告诉我可以用list(func1(column1)),结果却是[None, None]

【问题讨论】:

  • 谢谢你的建议,我的英语很差,但我会尽力学习如何问的部分。谢谢。

标签: python prettytable


【解决方案1】:

基于https://ptable.readthedocs.io/en/latest/tutorial.html 的教程,PrettyTable.add_column 就地修改了PrettyTable。此类函数通常返回None,而不是修改后的对象。

您还尝试使用map 和一个花哨的包装函数使问题过于复杂。下面的代码要简单得多,但会产生所需的结果。

import prettytable as pt
import numpy as np
import pandas as pd

column_names = ['data1', 'data2']

a = np.random.randn(30, 2)
b = a.round(2)
df = pd.DataFrame(b)
df.columns = column_names
tb = pt.PrettyTable()

for col in column_names:
    tb.add_column(col, df[col])

print(tb)

如果您仍然对了解map 返回的内容感兴趣,我建议您阅读有关iterablesiterators 的内容。 map 在调用函数的结果上返回一个迭代器,并且在你迭代它之前实际上不会做任何工作。

【讨论】:

  • 首先,非常感谢,结果满足我的需要。前天学习了wrapper函数的使用,可以有效解决复杂的问题。我用wrapper函数返回结果,我觉得在这些过程中不需要PrettyTable返回结果。
  • 抱歉,不清楚您是否要问其他问题。如果你是,请用新问题提交一个新问题。如果此答案有帮助,请将其标记为已接受。
  • import prettytable as pt import numpy as np import pandas as pd a=np.random.randn(30,2) b=a.round(2) df=pd.DataFrame(b) df. columns=['data1','data2'] df.index=pd.date_range('2017-1-1',periods=len(b),freq='M') tb = pt.PrettyTable() print(df .index,type(df.index)) print(df.head(),type(df)) print(df.columns.values) tb.add_column('dates',df.index) for col in df.columns。值:tb.add_column(col, df[col]) print(tb)
  • 我无法以正确的格式将代码添加到注释中。我从谷歌meta.stackexchange.com/questions/74784/…搜索答案,但它不起作用你能帮我吗。
  • 正如我之前提到的,如果您还有其他问题,您应该在新代码示例中提交一个新的、单独的问题。您不能也不应该将大型代码示例放入 cmets。
猜你喜欢
  • 1970-01-01
  • 2011-09-11
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多