简体   繁体   中英

Converting Python Dict containing list of lists into pandas Dataframe

I have the following code:

names = ['Tom', 'Dick', 'Harry']
marriageDates = ['02-02-1958', '08-07-1969', ['01-21-1973','07-14-1981']]
people = {
    "Name": names,
    "Marriage Date(s)": marriageDates
}
df = pd.DataFrame(people)
print(df)

which gives:

    Name             Marriage Date(s)
0    Tom                02-02-1958
1   Dick                08-07-1969
2  Harry  [01-21-1973, 07-14-1981]

However, I want the output to be:

    Name 1st Marriage Date 2nd Marriage Date
0    Tom        02-02-1958                  
1   Dick        08-07-1969                  
2  Harry        01-21-1973        07-14-1981

In other words, one of the keys in my dict is a list of lists. Rather than that key populate a column who's entries are lists (as in the last row in the first table), I want the nth elements of that list to be placed in new, adjacent columns (as in the second table). Is there anyway to do this?

You can try this:-

import pandas as pd
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])
names = ['Tom', 'Dick', 'Harry']
marriageDates = ['02-02-1958', '08-07-1969', ['01-21-1973','07-14-1981']]
people = {
    "Name": names,
    "Marriage Date(s)": marriageDates
}
df = pd.DataFrame(people)
marriage_date_df = df['Marriage Date(s)'].apply(pd.Series)
marriage_date_df = marriage_date_df.rename(columns = lambda x :  ordinal(x+1)+' Marriage Date')
result_df = pd.concat([df[["Name"]], marriage_date_df[:]], axis=1)
result_df

It gives output:-

    Name    1st Marriage Date   2nd Marriage Date
0   Tom     02-02-1958          NaN
1   Dick    08-07-1969          NaN
2   Harry   01-21-1973          07-14-1981

Hope this helps!!

There is a surprisingly easy way to do this. I recently found out about it too.

df2 = df['Marriage Date(s)'].apply(pd.Series)
pd.concat([df[['Name']], df2], axis=1).rename(columns={0:'1st Marriage Date',1:'2st Marriage Date'})

    Name    1st Marriage Date   2st Marriage Date
0   Tom     02-02-1958  NaN
1   Dick    08-07-1969  NaN
2   Harry   01-21-1973  07-14-1981

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM