在给定文件中查找列的数据类型,查找每列的最大值和最小值,如果是字符串,则根据长度查找最大值,最小值

时间:2020-04-25 19:11:56

标签: python string pandas list dataframe

给定文件的数据:

   Name     age   weight  
   John     21    78.5  
   kennedy  39    68.3   

预期输出:

col_name   dtype
Name       str    max: kennedy min: john
age        int    max: 39      min: 21
weight     float  max: 78.5    min: 68.3

****有人可以帮助我解决问题吗?**

我也尝试过此方法,但不知道如何找到它的最大,最小字符串,我只是为int,float做 。**

import pandas as pd

df=pd.read_csv(P1-UK-Bank-Customers.csv")

for col in df.select_dtypes([np.int8, np.int16, np.int32, np.int64, np.float]):

print('column: ', col)
print('max: ',df[col].max())
print('min: ',df[col].min())
print()**

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

def min_mx_dtype(x):
    return pd.Series(index=['min', 'max', 'dtype'],data=[x.min(), x.max(), x.dtype])

print(df.apply(min_mx_dtype).T.reset_index())

      index   min      max    dtype
0      Name  John  kennedy   object
1       age    21       39    int64
2  weight    68.3     78.5  float64

答案 1 :(得分:0)

您可以从字典列表创建数据框。然后以所需的任何格式打印出来。对于字符串,min和max等效于按升序排序的字符串列表中的第一个和最后一个值。

vals = []
for col in df.columns:
    vals.append({'col_name': col, 
                 'dtype': df[col].dtype,
                 'max': df[col].max(),
                 'min': df[col].min()})
df = pd.DataFrame(vals)

输出

  col_name    dtype      max   min
0     Name   object  kennedy  John
1      age    int64       39    21
2   weight  float64     78.5  68.3