合并除两个特定列之外的所有列元素

2024-09-24 22:18:16 发布

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

col != ['SourceFile','Label']

df['FileDescription']=df[col].apply(lambda row:'_'.join(row.values.astype(str)),axis=1)

我想合并除“SourceFile”和“Label”两列之外的所有列中的元素。我试过上面的代码。这导致了值错误。有这么多专栏。所以我不能用

col=['SourceFile','AggregationType','APP14Flags0','APP14Flags1','Application','ArchivedFileName','Artist',.....]
df['FileDescription']=df[col].apply(lambda row:'_'.join(row.values.astype(str)),axis=1)

Tags: lambda代码元素dfcollabelrowapply
1条回答
网友
1楼 · 发布于 2024-09-24 22:18:16

col != ['SourceFile','Label']在语法上是错误的,它给出的是名称错误,而不是值错误。 首先获取不需要的列并将其转换为set

col = set(['SourceFile','Label'])

现在将所有列设置为:

allCols = set(df.columns.to_list())

最后,将设置的差异作为列表分配回:

cols = list(set.difference(allCols, col))

现在您可以使用聚合方法:

df[col].astype(str).agg('_'.join)

参见示例执行:

df
     0    1    2    3    4    5     6     7     8     9
0  0.0  1.0  2.0  3.0  4.0  5.0   6.0   7.0   8.0   9.0
1  1.0  2.0  3.0  4.0  5.0  6.0   7.0   8.0   9.0  10.0
2  2.0  3.0  4.0  5.0  6.0  7.0   8.0   9.0  10.0  11.0
3  3.0  4.0  5.0  6.0  7.0  8.0   9.0  10.0  11.0  12.0
4  4.0  5.0  6.0  7.0  8.0  9.0  10.0  11.0  12.0  13.0

col= set([0])
allCols = set(df.columns.to_list())

col = list(set.difference(allCols, col))
df[col].astype(str).agg('_'.join, axis=1)
0        1.0_2.0_3.0_4.0_5.0_6.0_7.0_8.0_9.0
1       2.0_3.0_4.0_5.0_6.0_7.0_8.0_9.0_10.0
2      3.0_4.0_5.0_6.0_7.0_8.0_9.0_10.0_11.0
3     4.0_5.0_6.0_7.0_8.0_9.0_10.0_11.0_12.0
4    5.0_6.0_7.0_8.0_9.0_10.0_11.0_12.0_13.0
dtype: object

相关问题 更多 >