编辑并将多个列的值连接成一个列(pandas、python)

2024-04-29 09:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法,使用pandas和python将excel表中的几个列与已知的列名组合成一个新的、单一的列,并保留所有重要信息,如下面的示例所示:

输入:

ID,tp_c,tp_b,tp_p  
0,transportation - cars,transportation - boats,transportation - planes
1,checked,-,-
2,-,checked,-
3,checked,checked,-
4,-,checked,checked
5,checked,checked,checked

期望输出:

^{pr2}$

ID为0的行包含列内容的说明。理想情况下,代码将解析第二行中的描述,查找“-”,并将这些值连接到新的“tp\u all”列中。在


Tags: 方法信息id示例内容pandascarsexcel
3条回答

这很有趣,因为它是一个反面get_dummies。。。在

我想我应该手动修改列名,这样您就有了一个布尔数据帧:

In [11]: df1  # df == 'checked'
Out[11]:
    cars  boats planes
0
1   True  False  False
2  False   True  False
3   True   True  False
4  False   True   True
5   True   True   True

现在可以使用apply with zip:

^{pr2}$

现在您只需调整标题,以获得所需的csv。在

如果有一个更少的手动方式/更快的反向操作get_dummies。。。

好吧,一个更动态的方法:

In [63]:
# get a list of the columns
col_list = list(df.columns)
# remove 'ID' column
col_list.remove('ID')
# create a dict as a lookup
col_dict = dict(zip(col_list, [df.iloc[0][col].split(' - ')[1] for col in col_list]))
col_dict
Out[63]:
{'tp_b': 'boats', 'tp_c': 'cars', 'tp_p': 'planes'}
In [64]:
# define a func that tests the value and uses the dict to create our string
def func(x):
    temp = ''
    for col in col_list:
        if x[col] == 'checked':
            if len(temp) == 0:
                temp = col_dict[col]
            else:
                temp = temp + '+' + col_dict[col]
    return temp
df['combined'] = df[1:].apply(lambda row: func(row), axis=1)
df
Out[64]:
   ID                   tp_c                    tp_b                     tp_p  \
0   0  transportation - cars  transportation - boats  transportation - planes   
1   1                checked                     NaN                      NaN   
2   2                    NaN                 checked                      NaN   
3   3                checked                 checked                      NaN   
4   4                    NaN                 checked                  checked   
5   5                checked                 checked                  checked   

            combined  
0                NaN  
1               cars  
2              boats  
3         cars+boats  
4       boats+planes  
5  cars+boats+planes  

[6 rows x 5 columns]
In [65]:

df = df.ix[1:,['ID', 'combined']]
df
Out[65]:
   ID           combined
1   1               cars
2   2              boats
3   3         cars+boats
4   4       boats+planes
5   5  cars+boats+planes

[5 rows x 2 columns]

有一种方法:

newCol = pandas.Series('',index=d.index)
for col in d.ix[:, 1:]:
    name = '+' + col.split('-')[1].strip()
    newCol[d[col]=='checked'] += name
newCol = newCol.str.strip('+')

然后:

^{pr2}$

您可以使用此列创建一个新的数据帧,也可以对其执行任何操作。在

编辑:我看到你已经编辑了你的问题,这样运输方式的名称现在在第0行而不是列标题中。如果它们在列标题中(正如我的回答所假设的那样),并且您的新列标题似乎不包含任何其他有用的信息,那么您可能应该从将列名设置为第0行的信息开始,然后删除第0行。在

相关问题 更多 >