python-3.x - 对数据框进行单元格操作,确定精度

标签 python-3.x pandas

我有包含不同数据类型的数据框。 我想确定浮点类型的精度。 我只能使用以下代码选择 float64:

df_float64 = df.loc[:, df.dtypes == np.float64]

(不确定为什么也选择了仅具有“Nan”值的列,但这只是旁注)

现在要确定精度,我希望采用这种方法:

precision = len(cell.split(".")[1]

如果单元格是字符串。

并以 csv 形式输出,每列具有最大精度。

所以有这样的数据框:

|     A|     B|     C|     D|
|  0.01|0.0923|   1.0|   1.2|
| 100.1| 203.3| 1.093|   1.9|
|   0.0|  0.23|  1.03|   1.0|

我想要这个:

|     A|     B|     C|     D|
|     2|     4|     3|     1|

使用 Pandas 可以实现这一点吗?

谢谢

最佳答案

您可以使用:

  • fillna首先删除 NaNs
  • 通过 astype 转换为 str
  • 按列循环 apply或使用 lambda 函数的列表理解
  • 每列 split ,通过 str[1] 获取列表的第二个值并获取 len
  • 获取max值 - 输出是 Series
  • 如果需要,将Series转换为一行DataFrame

a = df.fillna(0).astype(str).apply(lambda x: x.str.split('.').str[1].str.len()).max()
print (a)
A    2
B    4
C    3
D    1
dtype: int64

df = a.to_frame().T
print (df)
   A  B  C  D
0  2  4  3  1

另一个解决方案:

df = df.fillna(0).astype(str)
a = [df[x].str.split('.').str[1].str.len().max() for x in df]

df = pd.DataFrame([a], columns=df.columns)
print (df)
   A  B  C  D
0  2  4  3  1

关于python-3.x - 对数据框进行单元格操作,确定精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45691943/

相关文章:

python - 在 Hadoop 上运行 MapReduce 程序仅输出一半的数据

python - 寻找共同角色

python - 薛定谔字典: getting values for dynamic keys on indirect access

python - Pandas 用 nan 值切割了一系列

python-3.x - python3 pySerial TypeError : unicode strings are not supported, 请编码为字节:

python-3.x - PyQt5:QAction功能可以通过QPushButton触发吗

python - 对数据框中的值进行排序

python - 在 Scikit 特征选择后保留特征名称

python - 猴子修补 pandas 和 matplotlib 以删除 df.plot() 的刺

python - 将 Pandas 数据框列和索引转换为值