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

Python 合并除两个特定列之外的所有列元素,python,pandas,dataframe,Python,Pandas,Dataframe,我想合并除“SourceFile”和“Label”两列之外的所有列中的元素。我试过上面的代码。这导致了值错误。有这么多专栏。所以我不能用 col != ['SourceFile','Label'] df['FileDescription']=df[col].apply(lambda row:'_'.join(row.values.astype(str)),axis=1) col!=['SourceFile','Label']语法错误,它给出的是名称错误而不是值错误。 首先获取不需要的列并将其

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

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

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

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

col=['SourceFile','AggregationType','APP14Flags0','APP14Flags1','Application','ArchivedFileName','Artist',.....]
df['FileDescription']=df[col].apply(lambda row:'_'.join(row.values.astype(str)),axis=1)
现在将所有列设置为:

col = set(['SourceFile','Label'])
最后,将设置的差异作为列表分配回:

allCols = set(df.columns.to_list())
现在您可以使用聚合方法:

cols = list(set.difference(allCols, col))
参见示例执行:

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

除了如何选择除这两列之外的所有dataframe之外,您的代码还可以。试试这个:
df.loc[:,~df.columns.isin(['SourceFile','Label'])。apply()…
剩下的就是你的代码。@Ashkang,你怎么能认为这种类型的赋值是col!=['SourceFile','Label']可以吗?我完全纠正了操作代码的这一部分。
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