gpt4 book ai didi

python - 使用列名称在所有列上应用函数 - Python、Pandas

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:38 25 4
gpt4 key购买 nike

基本上:

有没有办法在 Pandas 中应用使用数据框列名的函数?像这样:

df['label'] = df.apply(lambda x: '_'.join(labels_dict[column_name][x]), axis=1)

其中列名称是 apply 正在“处理”的列。

<小时/>

详细信息:

我想基于字典为数据帧的每一行创建一个标签。

让我们采用数据帧df:

df = pd.DataFrame({ 'Application': ['Compressors', 'Fans', 'Fans', 'Material Handling'],
'HP': ['0.25', '0.25', '3.0', '15.0'],
'Sector': ['Commercial', 'Industrial', 'Commercial', 'Residential']},
index=[0, 1, 2, 3])

应用标签后:

In [139]: df['label'] = df.apply(lambda x: '_'.join(x), axis=1)

In [140]: df
Out[140]:
Application HP Sector label
0 Compressors 0.25 Commercial Compressors_0.25_Commercial
1 Fans 0.25 Industrial Fans_0.25_Industrial
2 Fans 3.0 Commercial Fans_3.0_Commercial
3 Material Handling 15.0 Residential Material Handling_15.0_Residential

但是标签太长,尤其是当我考虑完整的数据帧时,其中包含更多的列。我想要的是使用字典来缩短来自列的字段(我在问题末尾粘贴了字典的代码)。

我可以对一个字段执行此操作:

In [145]: df['application_label'] = df['Application'].apply(
lambda x: labels_dict['Application'][x])

In [146]: df
Out[146]:
Application HP Sector application_label
0 Compressors 0.25 Commercial cmp
1 Fans 0.25 Industrial fan
2 Fans 3.0 Commercial fan
3 Material Handling 15.0 Residential mat

但我想对所有字段执行此操作,就像我在代码片段 #2 中所做的那样。所以我想做这样的事情:

df['label'] = df.apply(lambda x: '_'.join(labels_dict[column_name][x]), axis=1)

其中列名称是应用函数的 df 列。有没有办法获取这些信息?

感谢您的帮助!

<小时/>

我将字典定义为:

In [141]: labels_dict
Out[141]:
{u'Application': {u'Compressors': u'cmp',
u'Fans': u'fan',
u'Material Handling': u'mat',
u'Other/General': u'oth',
u'Pumps': u'pum'},
u'ECG': {u'Polyphase': u'pol',
u'Single-Phase (High LRT)': u'sph',
u'Single-Phase (Low LRT)': u'spl',
u'Single-Phase (Med LRT)': u'spm'},
u'Efficiency Level': {u'EL0': u'el0',
u'EL1': u'el1',
u'EL2': u'el2',
u'EL3': u'el3',
u'EL4': u'el4'},
u'HP': {0.25: 1.0,
0.33: 2.0,
0.5: 3.0,
0.75: 4.0,
1.0: 5.0,
1.5: 6.0,
2.0: 7.0,
3.0: 8.0,
10.0: 9.0,
15.0: 10.0},
u'Sector': {u'Commercial': u'com',
u'Industrial': u'ind',
u'Residential': u'res'}}

最佳答案

我想出了一种方法,但看起来很笨拙。我希望有更优雅的东西。

df['label'] = pd.DataFrame([df[column_name].apply(lambda x: labels_dict[column_name][x])
for column_name in df.columns]).apply('_'.join)

关于python - 使用列名称在所有列上应用函数 - Python、Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43745792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com