Home > database >  Split a DataFrame in several .txt on Pandas
Split a DataFrame in several .txt on Pandas

Time:11-17

I want to split a DataFrame based on two rows (Country and Brand) and create multiple .txt files for the combination of those two attributes. Basically, my DataFrame looks like this:

enter image description here

This is the code I created in case I want to split the result in to different excel files:

for (country, brand), group in df_f.groupby(['Country', 'Brand']):
        group.to_excel(f'{country}_{brand}.xlsx', index=False)

When I try to adapt this code with the following lines:

numpy_array = df_f.to_numpy()
np.savetxt("f'{country}_{brand}.txt", numpy_array, fmt = "%d")

However, it is not working. It says that this cannot be applied to a DataFrame.

How can I do this process?

CodePudding user response:

just use pandas.to_string() and save the output into a txt file:

for (country, brand), group in df_f.groupby(['Country', 'Brand']):
    s = group.to_string(index=False)
    with open(f'{country}_{brand}.txt', 'w') as f:
        f.write(s)
  • Related