Merging Lists of Different Format into Pandas DataFrame

Viewed 39

I have two different lists and an id:

id = 1
timestamps = [1,2,3,4]
values = ['A','B','C','D']

What I want to do with them is concatenating them into a pandas DataFrame so that:

id timestamp value
1 1 A
1 2 B
1 3 C
1 4 D

By iterating over a for loop I will produce a new set of two lists and a new ID with each iteration which should then be concatenated to the existing data frame. The pseudocode would look like this:

# for each sample in group:
    # do some calculation to create the two lists
    # merge the lists into the data frame, using the ID as index

What I tried to do so far is using concatenate like this:

pd.concat([
existing_dataframe, 
pd.DataFrame(
{
    "id": id, 
    "timestamp": timestamps, 
    "value": values}
)])

But there seems to be a problem that the ID field and the other lists are of different lengths. Thanks for your help!

1 Answers

Use:

pd.DataFrame(
{ 
    "timestamp": timestamps, 
    "value": values}
).assign(id=id).reindex(columns=["id", "timestamp", "value"])

Or:

df = \
 pd.DataFrame(
    { 
        "timestamp": timestamps, 
        "value": values}
    )
df.insert(column='id',value=id, loc=0)
Related