gpt4 book ai didi

python - 数据库到数据框并获取有关填充列的信息

转载 作者:行者123 更新时间:2023-11-29 13:02:20 25 4
gpt4 key购买 nike

我试图从我的 pandas 数据框中获取一些元数据:我想知道数据库的所有表中有多少行有数据。下面的代码给了我:

PandasError: DataFrame constructor not properly called! 

但我不知道为什么。它似乎破坏了一个根本没有数据的表,但我不明白为什么这会成为问题......

engine = sqlalchemy.create_engine("mysql+mysqldb://root:123@127.0.0.1/%s" % db)
meta = sqlalchemy.MetaData()
meta.reflect(engine)
tables = meta.tables.keys() # Fetches all table names
cnx = engine.raw_connection() # Raw connection is needed.

df = pd.read_sql('SELECT * FROM offending_table', cnx )
df = df.applymap(lambda x: np.nan if x == "" else x) # maak van alle "" een NaN

count = df.count()

table = pd.DataFrame(count, columns=['CellsWithData'])
table

完整的错误消息是:

offending_table
---------------------------------------------------------------------------
PandasError Traceback (most recent call last)
<ipython-input-367-f33bb79a6773> in <module>()
14 count = df.count()
15
---> 16 table = pd.DataFrame(count, columns=['CellsWithData'])
17 if len(all_tables) == 0:
18 all_tables = table

/Library/Python/2.7/site-packages/pandas/core/frame.pyc in __init__(self, data, index, columns, dtype, copy)
271 copy=False)
272 else:
--> 273 raise PandasError('DataFrame constructor not properly called!')
274
275 NDFrame.__init__(self, mgr, fastpath=True)

PandasError: DataFrame constructor not properly called!

提供此消息的表包含几列,其中没有数据。创建的 df 如下所示:

name           NaN
principal_id NaN
diagram_id NaN
version NaN
definition NaN

当我这样做时:

df.count()

我得到:

0

这是预期的行为吗?

最佳答案

看来 applymap 是这里的罪魁祸首:-)

read_sql 查询的结果集为空时,您将得到一个空数据帧。例如:

In [2]: df = pd.DataFrame(columns=list('ABC'))

In [3]: df
Out[3]:
Empty DataFrame
Columns: [A, B, C]
Index: []

使用这个空数据框,当您随后对此调用 applymap 时,它显然会转换为一个系列,然后计数只会给出一个数字:

In [10]: df2 = df.applymap(lambda x: np.nan if x == "" else x)

In [11]: df2
Out[11]:
A NaN
B NaN
C NaN
dtype: float64

In [12]: df2.count()
Out[12]: 0

直接在空数据帧上进行计数时会得到所需的输出:

In [13]: df.count()
Out[13]:
A 0
B 0
C 0
dtype: int64

我不知道 applymap 这样做的确切原因(或者它是否是一个错误),但现在一个简单的解决方案是在 applymap 之前快速执行一个 if :

if not len(df):
df = df.applymap(lambda x: np.nan if x == "" else x)

上述问题的原因是 DataFrame 构造函数不接受标量作为输入数据。

关于python - 数据库到数据框并获取有关填充列的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23171574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com