Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将多个行名称复制到列_Python_Pandas_Dataframe - Fatal编程技术网

Python 将多个行名称复制到列

Python 将多个行名称复制到列,python,pandas,dataframe,Python,Pandas,Dataframe,我导入了一个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 . . . . 我想添加一个新的专栏,以英国、美国等为值,如: area 1 2 3 4 UK a b c d UK

我导入了一个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
.    .    .    .
我想添加一个新的专栏,以英国、美国等为值,如:

area    1    2   3   4
UK      a    b   c   d
UK      b    d   c   a
 .      .    .   .   .
US      a    b   c   d
这需要适用于多个区域,其间包含不同数量的数据

提前谢谢

按位置用于新柱:

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
s(无第一列)的另一种解决方案:

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
按位置用于新柱:

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
s(无第一列)的另一种解决方案:

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
这里有一条路

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
这里有一条路

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

使用
df.insert(0,诸如此类)
如果订单材料我没有看到OP请求订单。使用
df.insert(0,诸如此类)
如果订单材料我没有看到OP请求订单。是否需要
区域作为第一列?或者最后一列不重要?是否需要
区域
作为第一列?还是最后一次都没关系?