【问题标题】:To find datatypes of column in a file given, to find max and min value of each column, in case of string find max, min string based on length在给定文件中查找列的数据类型,查找每列的最大值和最小值,如果是字符串,则根据长度查找最大值,最小值字符串
【发布时间】:2020-04-25 19:11:56
【问题描述】:

给定文件的数据:

   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()**

【问题讨论】:

  • 嗨 pooja,您需要为字符串定义 maxmin,然后才能给出任何答案
  • @DavidDR 实际上我想根据字符串的长度打印字符串的最大值、最小值。我不知道逻辑。帮我解决一下。

标签: python string pandas list dataframe


【解决方案1】:

试试这样的:

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

【讨论】:

  • 这很安静,但是您能否提供一个解决方案,根据字符串长度找到字符串的最大值、最小值。因为在以下字符串的情况下代码不起作用数据样本。客户 ID 姓名 姓 性别 年龄 地区 JobClassifi 加入日期 余额 0 100000001 Simon Walsh 男 21 英国白领 05.Jan.15 113810.15 1 400000002 Jasmine Miller 女 34 北爱尔兰蓝领 06.Jan.15 36919.73 2 100000003 Liam Brown 男 46 英格兰白领子 07.Jan.15 101536.83
【解决方案2】:

您可以从字典列表创建数据框。然后以您想要的任何格式打印出来。对于字符串,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

【讨论】:

  • 这很好,但是你能不能给出一个解决方案,根据字符串长度找到字符串的最大值,最小值。因为在以下字符串的情况下代码不起作用数据样本。客户 ID 姓名 姓 性别 年龄 地区 JobClassifi 加入日期 余额 0 100000001 Simon Walsh 男 21 英国白领 05.Jan.15 113810.15 1 400000002 Jasmine Miller 女 34 北爱尔兰蓝领 06.Jan.15 36919.73 2 100000003 Liam Brown 男 46 英格兰白领子 07.Jan.15 101536.83
猜你喜欢
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多