简体   繁体   English

在 Python 中重新格式化 DataFrame

[英]Reformatting DataFrame in Python

Below is the data frame I have:以下是我拥有的数据框:

ID  Char  Location
1   a      IN
2   b,c,d  US
3   e,g    IN
4   ,,,    CA

Below is the data frame I desire:下面是我想要的数据框:

ID   Char  Location
1    a      IN
2    b      US
2    c      US
2    d      US
3    e      IN
3    g      IN
4           CA

How can I transform this data frame?如何转换此数据框?

Try this:尝试这个:

df = pd.DataFrame({'ID': [1,2,3,4], 'Char': ['a', 'b,c,d', 'e,g', ',,,'], 'Location': ['IN', 'US', 'IN', 'CA']})

# copy the original order of columns
org_cols = df.columns.copy()

# explode Char column
df = df.drop(columns='Char').join(df['Char'].str.split(',').apply(lambda x: list(set(x))).explode())

# reorder columns
df = df[org_cols]
df

   ID Char Location
0   1    a       IN
1   2    c       US
1   2    b       US
1   2    d       US
2   3    e       IN
2   3    g       IN
3   4            CA    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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