[英]How to copy the column headers of a data frame to each row value?
I'm trying to transform a pandas data frame, applying a function to all values, to concatenate the column header and the actual value. 我正在尝试转换pandas数据帧,将函数应用于所有值,以连接列标题和实际值。
My original dataframe is something like this: 我的原始数据框是这样的:
|---------------------|------------------|
| Col1 | Col2 |
|---------------------|------------------|
| 12 | 34 |
|---------------------|------------------|
| 12 | 34 |
The output should be: 输出应该是:
|---------------------|------------------|
| Col1 | Col2 |
|---------------------|------------------|
| Col1_12 | Col2_34 |
|---------------------|------------------|
| Col1_12 | Col2_34 |
What I tried is this: 我试过的是这个:
mypandasdf.applymap(lambda x: 'columnname'+'_'+str(x))
But I'm struggling with the column name value. 但我正在努力争取列名值。 How can I put the real column name instead of a string? 如何将实际列名称而不是字符串? Or is there any other/better way to do it? 或者还有其他/更好的方法吗?
df = pd.DataFrame({'colA': [12,34], 'colB': [56,78]})
df = df.columns.values + '_' + df.astype(str)
print(df)
Output: 输出:
colA colB
0 colA_12 colB_56
1 colA_34 colB_78
Use DataFrame.columns
to access each column and concatenate as string to each value: 使用DataFrame.columns
访问每个列并将字符串连接到每个值:
for col in df.columns:
df[col] = col + '_' + df[col].astype(str)
print(df)
Col1 Col2
0 Col1_12 Col2_34
1 Col1_12 Col2_34
Convert each row in your dataframe as string and concat the column name: 将数据框中的每一行转换为字符串并连接列名:
df = pd.DataFrame({
"col1": [12 , 34],
'col2': [7,9]},)
for c in df:
df[c] = c + '_' + df[c].astype(str)
df
Result: 结果:
col1 col2
0 col1_12 col2_7
1 col1_34 col2_9
IIUC IIUC
df.apply(lambda x : x.name+'_'+x.astype(str))
Out[1323]:
Col1 Col2
0 Col1_12 Col2_34
1 Col1_12 Col2_34
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.