I have one dataframe contains a timestamp column and n number of value columns. I need to prepare two column dataframes with a timestamp column and a value column. That is total n number of dataframes. for example,
------------------------
|timestamp | A | B | C |
------------------------
| 1 |0.1|1.2|3.0|
| 2 |0.3|0.2|0.0|
Outputs
---------------
|timestamp| A |
---------------
|1 |0.1|
|2 |0.3|
---------------
|timestamp| B |
---------------
|1 |1.2|
|2 |0.2|
---------------
|timestamp| C |
---------------
|1 |3.0|
|2 |0.0|
I tried,
for i in range(len(df.columns)):
df1= df[['timestamp',df.columns]]
df1.to_csv('file.csv')
But got type error.
CodePudding user response:
Try:
for col in df.columns[1:]:
df[['timestamp', col]].to_csv(f'file_{col}.csv', index=False)
Output:
# file_A.csv
timestamp,A
1,0.1
2,0.3
# file_B.csv
timestamp,B
1,1.2
2,0.2
# file_C.csv
timestamp,C
1,3.0
2,0.0
CodePudding user response:
Just try this code:
dfs= []
for i in range(1, df.columns.shape[0] ):
new = pd.DataFrame(df.iloc[:, [0,i]])
dfs.append(new) #store them in variables
new.to_csv('file{}.csv'.format(i 1)) # save them to file
dfs[0] results in your first desired dataframe, etc.
dfs[0]
and file1.csv includes:
timestamp A
0 1 0.1
1 1 0.1
dfs[1]
and file2.csv includes:
timestamp B
0 1 1.2
1 1 1.2
and
dfs[2]
and file3.csv includes:
timestamp C
0 1 3.0
1 1 3.0