繁体   English   中英

熊猫多个行名称到列

[英]Pandas multiple row names to column

我已经导入了CSV数据集,但在重组数据时遇到了麻烦。 数据如下:

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

我想添加一个新列,其中包含UK,US等,例如:

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

这需要在多个区域之间使用不同数量的数据。

提前致谢。

这是一种方法

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

按位置insert用于新的列:

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

用于检查所有不带第一列的NaN的另一种解决方案:

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

暂无
暂无

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

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