我有一個df:
c1 c2 c3
A None A
B A None
C None None
None None None
如果相應的列不為空,我正在嘗試添加一個包含列名“c1-c3”的列
所以結果 df 應該是:
c1 c2 c3 c4
A None A c1|c3
B A None c1|c2
C None None c1
None None None None
建構式
data = {'c1': ['A', 'B', 'C', None],
'c2': [None, 'A', None, None],
'c3:':['A',None,None,None]}
df = pd.DataFrame(data)
uj5u.com熱心網友回復:
所以在你的情況下dot
df['new'] = df.notna().dot(df.columns '|').str[:-1]
Out[151]:
0 c1|c3
1 c1|c2
2 c1
3
dtype: object
uj5u.com熱心網友回復:
我認為這將滿足您的要求:
import pandas as pd
data = {'c1': ['A', 'B', 'C', None],
'c2': [None, 'A', None, None],
'c3':['A',None,None,None]}
df = pd.DataFrame(data)
df['c4'] = df.apply(lambda x: [df.columns[i] for i in range(len(df.columns)) if x[df.columns[i]] is not None], axis=1).str.join('|')
df.loc[df['c4'] == '', 'c4'] = None
print(df)
輸出:
c1 c2 c3 c4
0 A None A c1|c3
1 B A None c1|c2
2 C None None c1
3 None None None None
uj5u.com熱心網友回復:
不確定這是否是最優雅的方式,但它會起作用:
import re
def new_col(df):
col_value =''
if df['c1'] is None:
col_value = df_t.columns[0]
if df['c2'] is None:
col_value =col_value '|' df_t.columns[1]
if df['c3'] is None:
col_value =col_value '|' df_t.columns[2]
col_value = re.sub('^\|','',col_value )
return col_value
df['c4'] = df.apply(new_col,axis = 1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484973.html
上一篇:如何檢查熊貓列內的資料
