Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.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 - Fatal编程技术网

Python:仅更改具有上一列名的下一个未命名列

Python:仅更改具有上一列名的下一个未命名列,python,pandas,Python,Pandas,是否有任何方法可以为下一列指定下一个未命名列,而只为下一列指定上一列 输入: ca~ ch~ Campaign Type Code Channel Type Code Channel Type Definition 输出: ca~ ca~ ch~ ch~ Campaign Type Code Channel Type Code

是否有任何方法可以为下一列指定下一个未命名列,而只为下一列指定上一列

输入:

ca~                         ch~     
Campaign Type   Code    Channel Type    Code    Channel Type Definition
输出:

    ca~             ca~     ch~             ch~
    Campaign Type   Code    Channel Type    Code    Channel Type Definition
我尝试了下面的内容,但它填补了所有的空白,虽然我只想填补下一列,而不是另一个空白

x.columns = x.columns.to_series().mask(lambda y: y.str.startswith('Unnamed')).ffill()
样品

一种方法可以做到这一点

df.columns = [df.columns[i-1] if 'Unnamed' in df.columns[i] else df.columns[i] for i in range(len(df.columns))]

备选方案

首先将“Unnamed”替换为NaN,然后将ffill替换为limit=1

df.columns = list(pd.DataFrame(df.columns).replace('Unnamed\.?\d?',np.nan,regex=True).ffill(limit=1)[0])


频道类型定义应该为空?@PV8是的,所以我只想填充下一列,而不是另一个未命名的下一列
             ca~   ca~           ch~   ch~                Unnamed.1
0  Campaign Type  Code  Channel Type  Code  Channel Type Definition
df.columns = list(pd.DataFrame(df.columns).replace('Unnamed\.?\d?',np.nan,regex=True).ffill(limit=1)[0])
    ca~   ca~           ch~   ch~                      NaN
0  Campaign Type  Code  Channel Type  Code  Channel Type Definition