python - 使用不同类型的单单元阵列清理数据框列

标签 python pandas dataframe numpy

我正在处理一个具有多列的大型数据框。但是,某些列的数据采用数组形式(单值)。我需要仅使用单元格值转换数据框列,即没有数组元素样式。我尝试过以不同的方式压平、挤压,但无法以我想要的方式获得输出。 以下代码重现了我目前正在使用的数据格式:

import pandas as pd
a = [[[10]],[[20]],[[30]],[[40]]]
b=[[50],[60],[70],[80]]
c=[90,100,110,120]
df = pd.DataFrame(list(zip(a,b,c)),columns=['a','b','c'])
print(df)

上面的输出是:

        a     b    c
0  [[10]]  [50]   90
1  [[20]]  [60]  100
2  [[30]]  [70]  110
3  [[40]]  [80]  120

但是,我希望得到如下输出:

    a   b    c
0  10  50   90
1  20  60  100
2  30  70  110
3  40  80  120

如果您能建议如何解决这个问题,那将会非常有帮助。

实际数据帧的头部如下所示:

           acoeff         bcoeff  refdiff  ref18
0  [[0.33907555]]  [11.51908656]    0.000  0.001
1  [[0.34024954]]  [11.45693353]    0.001  0.001
2  [[0.34134777]]  [11.40045124]    0.002  0.001
3  [[0.34297324]]  [11.33036004]    0.004  0.001
4  [[0.34373931]]   [11.2991075]    0.005  0.001

字典格式的头部如下:

{'acoeff': {0: '[[0.33907555]]', 1: '[[0.34024954]]', 2: '[[0.34134777]]', 3: '[[0.34297324]]', 4: '[[0.34373931]]'}, 'bcoeff': {0: '[11.51908656]', 1: '[11.45693353]', 2: '[11.40045124]', 3: '[11.33036004]', 4: '[11.2991075]'}, 'refdiff': {0: 0.0, 1: 0.001, 2: 0.002, 3: 0.004, 4: 0.005}, 'ref18': {0: 0.001, 1: 0.001, 2: 0.001, 3: 0.001, 4: 0.001}}

最佳答案

字符串

去掉[]并转换为数字:

(df.update(df.select_dtypes(exclude='number')
             .apply(lambda c: pd.to_numeric(c.str.strip('[]'))))
 )
print(df)

真实列表

您可以使用 str 定位器取消列表的嵌套:

df['a'].str[0].str[0]

输出:

0    10
1    20
2    30
3    40
Name: a, dtype: int64

要使事情自动化一点,您可以使用递归函数:

def unnest(x):
    from pandas.api.types import is_numeric_dtype
    if is_numeric_dtype(x):
        return x
    else:
        return unnest(x.str[0])

df2 = df.apply(unnest)

使用每个系列的第一项来确定嵌套级别的变体:

def unnest(x):
    from pandas.api.types import is_numeric_dtype
    if len(x)>0 and isinstance(x.iloc[0], list):
        return unnest(x.str[0])
    else:
        return x

df2 = df.apply(unnest)

输出:

    a   b    c
0  10  50   90
1  20  60  100
2  30  70  110
3  40  80  120
任意嵌套

如果每个单元格都有任意嵌套,则可以对每个元素使用相同的逻辑:

def unnest(x):
    if isinstance(x, list) and len(x)>0:
        return unnest(x[0])
    else:
        return x
    
df2 = df.applymap(unnest)

关于python - 使用不同类型的单单元阵列清理数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72202329/

相关文章:

python - 我收到此错误 --> TypeError : string indices must be integers

python - 更改 Pandas Dataframe 中的列值以将数字显示为百万

python - 带有类别的 pyplot 条形图

python - Pandas - 连接两个多索引数据帧

r - 分组并计数以获得接近的价格

python - 解释一下这行代码(列表)

python - Django,截断不正确的 DOUBLE 值 : '\x00' in ValueQuerySet

python - 将 Set 拆分为多列 Pandas Python

python - python中的变量范围和Try Catch

python - 无法将非有限值(NA 或 inf)转换为整数