Home > Blockchain >  How to split data of different types in a row into separate columns using pandas
How to split data of different types in a row into separate columns using pandas

Time:10-22

I'm looking to split data of different types which are within the same column into seperate columns using pandas. I have the below data

ID;Number;position
123;97529;30
123;234390;30
123;9034;1
456;90273;3028

My ultimate goal is to print plots such that there is a separate plots for 123 & 456. I am able to print all of them on the same plot, but am unable to split up the data for separate plotting.

CodePudding user response:

If I understand your question correctly, you can iterate over the unique values in ID, filter the dataframe to hold only records with such an ID and plot -

for value in df['ID'].unique():
    df.loc[df['ID']==value].plot(...)

CodePudding user response:

You can do something like this:

df[['ID', 'Number', 'position']] = df['ID;Number;position'].str.split(';',expand=True)

CodePudding user response:

Output: {'123': [('97529', '30'), ('234390', '30'), ('9034', '1')], '456': [('90273', '3028')]}

Code:

import sys
import csv

def main():
    data={}
    with open("filename.txt", "r") as f:
        reader = csv.reader(f, delimiter=";")
        for id,number,position in reader:
            if id == 'ID':
                continue
            if not id in data:
                data[id] = []
            data[id].append((number, position))

    print(data)

if __name__ == "__main__":
    sys.exit(main())
  • Related