ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Recursively get message field names in ROS2

asked 2021-09-16 03:44:48 -0500

KenYN gravatar image

updated 2021-09-16 03:45:23 -0500

We have the handy rosidl_runtime_py.message_to_csv() method for converting a message to CSV, but is there a similar function that will recursively get the field names so I can print out a CSV header as well?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
0

answered 2021-09-16 22:35:16 -0500

KenYN gravatar image

Solved it!

def recursive_items(ordered_dict):
    for key, value in ordered_dict.items():
        if type(value) is collections.OrderedDict:
            yield from recursive_items(value)
        else:
            yield (key, value)

def print_headers(record):
    print(','.join([key for key, _ in recursive_items(rosidl_runtime_py.message_to_ordereddict(record))]))

I'd missed the API rosidl_runtime_py.message_to_ordereddict() which gives me the message with names and values in a nested OrderedDict, so I iterate over that to pull out the keys from the leaf nodes.

edit flag offensive delete link more
0

answered 2021-09-16 04:05:50 -0500

Ranjit Kathiriya gravatar image

updated 2021-09-16 04:06:06 -0500

Just have a look at this question: #q379915, I hope you will get your solution. Instead, you also can use the Pandas library for printing header in a recursive manner.

edit flag offensive delete link more

Comments

That's the wrong way round - I want to go from Bag to CSV, not CSV to Bag.

KenYN gravatar image KenYN  ( 2021-09-16 18:35:53 -0500 )edit

Ohh! I am sorry, but It should be easy you just have collected data in the last and in the end you can store it to CSV. I preferred to use pandas because it is faster the normal way of code.

def write_csv():
    df2 = pd.DataFrame()
    for name, df in data.items():
        df2 = df2.append(df)
    df2.to_csv('mydf.csv')
Ranjit Kathiriya gravatar image Ranjit Kathiriya  ( 2021-09-17 01:38:48 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2021-09-16 03:44:48 -0500

Seen: 346 times

Last updated: Sep 16 '21