简体   繁体   中英

Pandas multiple row names to column

I have imported a CSV dataset and am having trouble restructuring the data. The data looks like:

1    2    3    4
UK   NaN  NaN  NaN
a    b    c    d
b    d    c    a
.    .    .    .
US   NaN  NaN  NaN
a    b    c    d
.    .    .    .

I would like to add a new column with UK, US etc as the value like:

area    1    2   3   4
UK      a    b   c   d
UK      b    d   c   a
 .      .    .   .   .
US      a    b   c   d

This needs to work for multiple areas with different numbers of data in between.

Thanks in advance.

Here's one way

In [4461]: nn =  df['2'].notnull()

In [4462]: df[nn].assign(area=df['1'].mask(nn).ffill())
Out[4462]:
   1  2  3  4 area
1  a  b  c  d   UK
2  b  d  c  a   UK
4  a  b  c  d   US

Use insert for new colum by position:

print (df[1].where(df[2].isnull()).ffill())
0    UK
1    UK
2    UK
3    US
4    US
Name: 1, dtype: object

df.insert(0, 'area', df[1].where(df[2].isnull()).ffill())
#alternative
#df.insert(0, 'area', df[1].mask(df[2].notnull()).ffill())
df = df[df[1] != df['area']].reset_index(drop=True)
print (df)
  area  1  2  3  4
0   UK  a  b  c  d
1   UK  b  d  c  a
2   US  a  b  c  d

Another solution for check all NaN s without first column:

print (df[1].where(df.iloc[:, 1:].isnull().all(1)).ffill())
0    UK
1    UK
2    UK
3    US
4    US
Name: 1, dtype: object

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