打印数据框的列位置 [英] print column position of a dataframe
本文介绍了打印数据框的列位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的数据框:
c_id string1 age salary string2
1 apple 21 21.22 hello_world
2 orange 41 23.4 world
3 kiwi 81 20.22 hello
我需要打印具有max_len的字符串值以及列数据类型,名称及其位置.因此,我的预期输出应为:
i need to print the string value which has max_len along with the column datatype, name and its position.so my expected output should be:
position c_name c_dtype max_len
1 string1 object orange
4 string2 object hello_world
我尝试了这些概念来根据字符串的最大长度打印字符串值.
i tried these concept to print string value based on its max length.
for col in df.select_dtypes([np.object]):
max_len = max(df[col], key=len)
print('prints col_name:', col)
print('prints the datatype ',df[col].dtype)
print('prints the maximum length string value',max_len)
我需要合并所有这些内容,并且应该获得如上所述的预期输出.
i need to merge all these and should get my expected output as mentioned above.
推荐答案
Use Index.get_loc
for position of column:
out = []
for col in df.select_dtypes([np.object]):
max_len = max(df[col], key=len)
print('position:', df.columns.get_loc(col))
print('prints col_name:', col)
print('prints the datatype ',df[col].dtype)
print('prints the maximum length string value',max_len)
out.append({'position':df.columns.get_loc(col),
'c_name': col, 'c_dtype':df[col].dtype, 'max_len': max_len})
df1 = pd.DataFrame(out)
print (df1)
position c_name c_dtype max_len
0 1 string1 object orange
1 4 string2 object hello_world
列表理解解决方案:
out = [{'position':df.columns.get_loc(col),
'c_name': col, 'c_dtype':df[col].dtype, 'max_len': max(df[col], key=len)}
for col in df.select_dtypes([np.object])]
df1 = pd.DataFrame(out)
print (df1)
position c_name c_dtype max_len
0 1 string1 object orange
1 4 string2 object hello_world
这篇关于打印数据框的列位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文