我需要一个数据被,拆分的单线CSV。我的问题是,当我尝试使用apply遍历我的Dataframe时,我得到了一个Series对象,to_csv方法给了我一个拆分成行的str,将None设置为"",没有任何,。但是,如果我使用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=','),但我得到了相同的输出。
在DataFrame和Series中使用to_csv方法时,为什么会得到不同的输出
需要做哪些更改才能使apply产生与for相同的结果
发布于 2021-04-23 22:28:18
嗯,我研究了很多,我的输出是不同的,因为这是预期的行为。我在Pandas存储库中发现了一个PR,其中一些贡献者使用Series.to_csv添加了一个片段,并具有与我相同的输出(This the comment from toobaz)。
因为序列是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)在apply中使用问题中的DataFrame (使用示例数据)调用的print_csv的新输出是我所期望的:
<class 'pandas.core.frame.DataFrame'>
,0.32,0.43
<class 'pandas.core.frame.DataFrame'>
,0.23,0.12https://stackoverflow.com/questions/67214578
复制相似问题