我需要一个由 ,
分割数据的单行 CSV。我的问题是,当我尝试使用 apply 迭代我的 Dataframe 时,我得到一个 Series
对象,to_csv
方法给我一个 str
分成几行,将 None
设置为""
并且没有任何 ,
。但是如果我用 for
遍历数据框,我的方法会得到一个 Dataframe
对象,并且它给我一个 str
与 ,
一行,而不设置 { {1}} 到 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=',')
和 to_csv
中使用 DataFrame
方法时得到不同的输出?
需要进行哪些更改才能使 Series
产生与 apply
相同的结果?
答案 0 :(得分:1)
嗯,我研究了很多,我的输出是不同的,因为这是预期的行为。我在 Pandas 存储库中找到了一个 PR,其中一些贡献者添加了一个带有 Series.to_csv
的片段,并且具有与我相同的输出 (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 的访问器)。>
我将应用函数更改为:
df.apply(lambda x: print_csv(x.to_frame().T), axis=1)
print_csv
中使用问题中的 DataFrame 调用的 apply
的新输出(带有示例数据)正是我所期望的:
<class 'pandas.core.frame.DataFrame'>
,0.32,0.43
<class 'pandas.core.frame.DataFrame'>
,0.23,0.12