【问题标题】:Why pandas Dataframe.to_csv has a different output as Series.to_csv?为什么 pandas Dataframe.to_csv 的输出与 Series.to_csv 不同?
【发布时间】:2021-07-16 18:05:56
【问题描述】:

我需要一个单行 CSV,其中的数据由 , 分割。我的问题是,当我尝试使用 apply 迭代我的 Dataframe 时,我得到一个 Series 对象,而 to_csv 方法给了我一个 str 分成几行,将 None 设置为 "" 并且没有任何 @987654327 @。但是,如果我用for 遍历数据框,我的方法会得到一个Dataframe 对象,它给我一个str, 在一行中,而没有将None 设置为""

这是一个测试代码:

import pandas


def print_csv(tabular_data):
    print(type(tabular_data))
    csv_data = tabular_data.to_csv(header=False, index=False)
    print(csv_data)


df = pandas.DataFrame([
    {"a": None, "b": 0.32, "c": 0.43},
    {"a": None, "b": 0.23, "c": 0.12},
])

df.apply(lambda x: print_csv(x), axis=1)

for i in range(0, df.shape[0]):
    print_csv(df[i:i+1])

控制台输出使用apply:

<class 'pandas.core.series.Series'>
""
0.32
0.43
<class 'pandas.core.series.Series'>
""
0.23
0.12

控制台输出使用for:

<class 'pandas.core.frame.DataFrame'>
,0.32,0.43
<class 'pandas.core.frame.DataFrame'>
,0.23,0.12

我尝试在我的函数中使用csv_data = tabular_data.to_csv(header=False, index=False, sep=','),但得到了相同的输出。

当我在 DataFrameSeries 中使用 to_csv 方法时,为什么会得到不同的输出?

需要进行哪些更改以使applyfor 给出相同的结果?

【问题讨论】:

  • DataFrame.apply 传递一个系列,无论轴=0 是列系列,还是轴=1 是变成系列的行。据我所知,你无法改变这一点
  • 你为什么需要apply 你不能只做df.to_csv(header=False, index=False) 吗?
  • @ALollz 是的,我知道,但我不知道为什么这两个to_csv 方法会给出不同的结果。
  • @BioGeek 我需要逐行迭代以将行作为 CSV 发送到一对一的 Sagemaker 端点以进行推断。
  • @FrancoMorero 然后遍历 csv 的行:for line in df.to_csv(header=False, index=False).splitlines(): ...

标签: python python-3.x pandas dataframe csv


【解决方案1】:

嗯,我研究了很多,我的输出是不同的,因为这是预期的行为。我在 Pandas 存储库中找到了一个 PR,其中一些贡献者添加了一个带有 Series.to_csv 的 sn-p,并且具有与我相同的输出 (This the comment from toobaz)。

因为 Series 是 DataFrame 单列的数据结构,所以我的 print_csv 函数真正得到的是包含我的数据的单列数据结构(这是 print(tabular_data.head())print_csv 内的输出当使用df.apply(lambda x: print_csv(x), axis=1) 调用一个对象时):

<class 'pandas.core.series.Series'>
a    None
b    0.23
c    0.12
Name: 1, dtype: object

所以,CSV 可以这样,因为它每列生成一行:

""
0.23
0.12

要获得我想要的输出,我需要做的是将单列数据结构更改为单行数据结构。为此,我使用pandas.Series.to_frame 将Series 对象转换为DataFrame 并将其转置(我使用DataFrame 的属性T,它是pandas.DataFrame.transpose 的访问器)。

我把apply函数改成:

df.apply(lambda x: print_csv(x.to_frame().T), axis=1)

apply 中调用print_csv 的新输出以及问题中的DataFrame(带有示例数据)是我所期望的:

<class 'pandas.core.frame.DataFrame'>
,0.32,0.43
<class 'pandas.core.frame.DataFrame'>
,0.23,0.12

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2021-04-26
    • 2021-08-29
    • 1970-01-01
    • 2020-10-01
    • 2016-10-10
    • 2015-01-04
    相关资源
    最近更新 更多