I have a pandas dataframe that has variable number of columns like C1, C2, C3, F1, F2... F100. I need combine F1, F2 .. F100 into one column of dict/map data type as follows. How can I do it using pandas? C1, C2, C3 are fixed name columns while F1, F2, F100 are variable.
Input:
C1 C2 C3 F1 F2 F100
"1" "2" "3" "1" "2" "100"
Output:
C1 C2 C3 Features
"1" "2" "3" {"F1":"1", "F2":"2", "F100": "100"}
filter
+ to_dict
df['Features'] = df.filter(like='F').to_dict('records')
df
C1 C2 C3 C4 F1 F2 F3 F4 Features
0 1 2 3 4 5 6 7 8 {'F1': '5', 'F2': '6', 'F3': '7', 'F4': '8'}
1 x y z w r e s t {'F1': 'r', 'F2': 'e', 'F3': 's', 'F4': 't'}
2 a b c d d f g h {'F1': 'd', 'F2': 'f', 'F3': 'g', 'F4': 'h'}
If you use pandas, you can use df.apply()
function doing so.
Code would be like:
def merge(row):
result = {}
for idx in row.index:
if idx.startswith('F'):
result[idx] = row[idx]
print(result)
return result
df['FEATURE'] = df.apply(lambda x: merge(x), axis=1)
Results:
C1 C2 C3 F1 F2 F100 FEATURE
0 1 2 3 1 2 100 {'F1': 1, 'F100': 100, 'F2': 2}
1 11 21 31 11 21 1001 {'F1': 11, 'F100': 1001, 'F2': 21}
2 12 22 32 2 22 2002 {'F1': 2, 'F100': 2002, 'F2': 22}
Consider the following example.
d = pd.DataFrame([list('12345678'), list('xyzwrest'), list('abcddfgh')], columns = 'C1, C2, C3, C4, F1, F2, F3, F4'.split(', '))
d
>>> C1 C2 C3 C4 F1 F2 F3 F4
0 1 2 3 4 5 6 7 8
1 x y z w r e s t
2 a b c d d f g h
Let us define the Features
column as follows:
d['Features'] = d.apply(lambda row: {feat: val for feat, val in row.items() if feat.startswith('F')}, axis =1)
#so that when we call d the results will be
d
>>> C1 C2 C3 C4 F1 F2 F3 F4 Features
0 1 2 3 4 5 6 7 8 {'F1': '5', 'F2': '6', 'F3': '7', 'F4': '8'}
1 x y z w r e s t {'F1': 'r', 'F2': 'e', 'F3': 's', 'F4': 't'}
2 a b c d d f g h {'F1': 'd', 'F2': 'f', 'F3': 'g', 'F4': 'h'}
I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.