小编Cal*_*ari的帖子

Python Pandas推断列数据类型

我正在将JSON文件读入数据帧.数据框可能包含一些String(对象)类型列,一些Numeric(int64和/或float64)以及一些日期时间类型列.读入数据时,数据类型通常不正确(即datetime,int和float通常存储为"object"类型).我想报告这种可能性.(即列在数据帧中为"object"(String),但它实际上是"datetime").

我遇到的问题是,当我使用pd.to_numericpd.to_datetime时,他们将评估并尝试转换列,并且很多次它最终取决于我最后调用的两个中的哪一个...(我打算使用convert_objects()可以使用,但是这是折旧的,所以想要一个更好的选择).

我用来评估数据帧列的代码是(我意识到下面的很多内容是多余的,但为了便于阅读,我已经用这种方式编写了代码):

try:
   inferred_type = pd.to_datetime(df[Field_Name]).dtype
   if inferred_type == "datetime64[ns]":
      inferred_type = "DateTime"
except:
   pass
try:
   inferred_type = pd.to_numeric(df[Field_Name]).dtype
   if inferred_type == int:
      inferred_type = "Integer"
   if inferred_type == float:
      inferred_type = "Float"
except:
   pass
Run Code Online (Sandbox Code Playgroud)

python profiling pandas

10
推荐指数
4
解决办法
6571
查看次数

当列中有字符串时,如何从熊猫列中获取最长长度的字符串/整数/浮点数

我有一个包含多列数据和不同类型的数据框。我遇到了一列,其中包含字符串和整数。我试图找到最长/最短长度的值(注意不是最大值)。(注意:我在下面使用的例如只有整数,因为我无法弄清楚如何混合 dtypes 并且仍然称其为 int64 列)

    Name    MixedField
a   david   32252
b   andrew  4023
c   calvin  25
d   david   2
e   calvin  522
f   david   35
Run Code Online (Sandbox Code Playgroud)

我使用的方法是将 df 列转换为字符串系列(因为它们可能是 double/int/string/combinations),然后我可以从这个系列中获取最大/最小长度项:

df['MixedField'].apply(str).map(len).max()
df['MixedField'].apply(str).map(len).min()
Run Code Online (Sandbox Code Playgroud)

但是不知道如何选择最大和最小长度的实际值!?!(即32252(最长)和2(最短)

(我可能不需要解释这一点,但最大和最长之间存在细微差别......(即“aa”比“z”长))。感谢你的帮助。谢谢。

python pandas

5
推荐指数
1
解决办法
7754
查看次数

标签 统计

pandas ×2

python ×2

profiling ×1