Home > database >  change the structure of a pandas dataframe, move header to a column
change the structure of a pandas dataframe, move header to a column

Time:09-21

I got a dataframe like below from an API: enter image description here

I want to change its structure to have a dataframe with a column for time, a column for name and a column for the float value. Any hints?

CodePudding user response:

Not sure if this is what you're asking (not a whole lot of info provided), but you can try and transpose the dataframe. This will flip rows to columns and columns to rows

df.T

CodePudding user response:

IIUC:

Input data:

>>> df
       Time  23-30-17 19:00:00  12-30-17 20:00:00  12-30-17 21:00:00
222  County                  1                  2                  3
227    Farm                  4                  5                  6
df = df.set_index('Time').stack().reset_index()
df.columns = ['Name', 'Time', 'Value']

Output result:

>>> df
     Name               Time  Value
0  County  23-30-17 19:00:00      1
1  County  12-30-17 20:00:00      2
2  County  12-30-17 21:00:00      3
3    Farm  23-30-17 19:00:00      4
4    Farm  12-30-17 20:00:00      5
5    Farm  12-30-17 21:00:00      6
  • Related