如何将 Python 数据框类型的 float64 列拆分为多列

How to split Python dataframe type float64 column into multiple columns

我需要使用 pyodbc 运行 对从销售 table 中提取的一些数据进行一些计算。我能够提取数据,然后我想我会将它加载到 pandas 数据框中。当数据框加载时,它在一列中包含我的数据,而实际上它是 5 个单独的列。

query = """SELECT OD.OrderNum, OD.Discount,OD.OrderQty,OD.UnitPrice, (a.OurReqQty - (a.OurJobShippedQty + a.OurStockShippedQty)) AS RemainingQty
        FROM PUB.OrderDtl AS OD
        INNER JOIN PUB.OrderRel AS a ON (OD.Company = a.Company) AND (OD.OrderNum = a.OrderNum) AND (OD.OrderLine = a.OrderLine)
        WHERE (a.OpenRelease = 1)"""
print (query)
cnxn = pyodbc.connect(connection_string)
cursor = cnxn.cursor()
cursor.execute(query)
ab = list(cursor.fetchall())
df = pd.DataFrame(ab, columns=["remain"])

哪个returns这个。

[(115702, Decimal('0.00'), Decimal('25.00'), Decimal('145.00000'), Decimal('25.00')), 
(115793, Decimal('0.00'), Decimal('20.00'), Decimal('823.00000'), Decimal('20.00')),
(115793, Decimal('0.00'), Decimal('20.00'), Decimal('823.00000'), Decimal('20.00')), 
(116134, Decimal('0.00'), Decimal('10.00'), Decimal('587.00000'), Decimal('5.00')),
(116282, Decimal('0.00'), Decimal('1.00'), Decimal('699.95000'), Decimal('1.00'))]

当我将其加载到数据框中时,它看起来像这样。

                          remain
0  [115702, 0.00, 25.00, 145.00000, 25.00]
1  [115793, 0.00, 20.00, 823.00000, 20.00]
2  [115793, 0.00, 20.00, 823.00000, 20.00]
3   [116134, 0.00, 10.00, 587.00000, 5.00]
4    [116282, 0.00, 1.00, 699.95000, 1.00]

我试图通过

将其转换为字符串
df.index = df.index.map(str)
df_split = df["remain"].str.split(', ', 1)

但我的分裂看起来像

0   NaN
1   NaN
2   NaN
3   NaN
4   NaN

我知道这是一个格式问题,或者我认为是,但我不知道从哪里开始。我认为如果它是一个字符串,它会最容易拆分,但也许我遗漏了一些东西。

认为这个 post 会有所帮助,但我认为它需要我导出然后重新读取数据。

如有任何帮助,我将不胜感激。

试试这个:

col_names = ['OrderNum', 'Discount', 'OrderQty', 'UnitPrice', 'RemainingQty']
df_split = pd.DataFrame(df['remain'].values.tolist(), columns=col_names)

[出]

   OrderNum  Discount  OrderQty  UnitPrice  RemainingQty
0    115702       0.0      25.0     145.00          25.0
1    115793       0.0      20.0     823.00          20.0
2    115793       0.0      20.0     823.00          20.0
3    116134       0.0      10.0     587.00           5.0
4    116282       0.0       1.0     699.95           1.0

您看到的行为是由于 pyodbc 中的 .fetchall() 不是 return 元组列表,它 return 是 pyodbc.Row 对象列表.

您应该可以使用 pandas' read_sql 方法直接填充您的 DataFrame:

query = """\
SELECT OD.OrderNum,
    OD.Discount,
    OD.OrderQty,
    OD.UnitPrice,
    (a.OurReqQty - (a.OurJobShippedQty + a.OurStockShippedQty)) AS RemainingQty
FROM PUB.OrderDtl AS OD
INNER JOIN PUB.OrderRel AS a ON (OD.Company = a.Company)
    AND (OD.OrderNum = a.OrderNum)
    AND (OD.OrderLine = a.OrderLine)
WHERE (a.OpenRelease = 1)
"""
cnxn = pyodbc.connect(connection_string)
df = pd.read_sql(query, cnxn)