I need a one-line CSV with data split by a ,. My problem is when I try to iterate over my Dataframe using apply, I get a Series object and the to_csv method gives me one str split into lines, setting None as "" and without any ,. But if I iter over the data frame with for, my method gets a Dataframe object, and it gives me one str in one line with the ,, without setting None to "".
Here is a code to test this:
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])
console output using apply:
<class 'pandas.core.series.Series'>
""
0.32
0.43
<class 'pandas.core.series.Series'>
""
0.23
0.12
console output using for:
<class 'pandas.core.frame.DataFrame'>
,0.32,0.43
<class 'pandas.core.frame.DataFrame'>
,0.23,0.12
I tried with csv_data = tabular_data.to_csv(header=False, index=False, sep=',') in my function but I got the same output.
Why am I getting different output when I use the to_csv method in a DataFrame and in a Series?
What are the changes that need to make so apply gives the same result as the for?