pandas ValueError:找不到有效的数字字!请输入有效的数字字(例如:2023049)

cbjzeqam  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(77)

如何划分栏目和栏目中的数据,我附呈以供参考。
范例:列cement_water的值为302; 203.0,必须拆分为两列,分别命名为cement和water,值为302.0和203.0。列值具有不同的delimeter(;,_),必须处理,并且值具有字符串数据,必须使用word to number转换为数值。

Previous/Default such columns:

cement_water                  coarse_fine_aggregate
three hundred and two;203.0     974.0,817.0
one hundred and fifty-one;184.4     992.0;815.9
three hundred and sixty-two_164.9   944.7;755.8

Has to be converted into the following:

cement  water   coarse_aggregate    fine_aggregate
302.0   203.0     974.0                    817.0
151.0   184.4      992.0               815.9
362.0   164.9      944.7               755.8

个字符
错误-找不到有效的数字字!请输入有效的数字字(例如:二百二十三万零四十九)

gk7wooem

gk7wooem1#

这对我来说是一个很好的方法,使用这个变体:

from word2number import w2n

out = (pd.concat([df['cement_water'].str.extract(r'(?P<cement>.*)[;,_](?P<water>\d+.?\d*)$'),
                  df['coarse_fine_aggregate'].str.split('[;,]', expand=True)
                   .rename(columns={0: 'coarse_aggregate', 1: 'fine_aggregate'})], axis=1)
         .assign(cement=lambda d: d['cement'].map(w2n.word_to_num))
         .astype(float)
      )

字符串
输出量:

cement  water  coarse_aggregate  fine_aggregate
0   302.0  203.0             974.0           817.0
1   151.0  184.4             992.0           815.9
2   362.0  164.9             944.7           755.8

更多通用代码,并提供额外示例

在这里,cement_water中混合了字符串和数字,让我们首先识别数字并只解析字符串:

tmp = df['cement_water'].str.extract(r'(?P<cement>.*)[;,_](?P<water>\d+.?\d*)$')
s = pd.to_numeric(tmp['cement'], errors='coerce')
m = s.isna() & df['cement_water'].notna()
tmp.loc[m, 'cement'] = df.loc[m, 'cement_water'].map(w2n.word_to_num)

out = (pd.concat([tmp,
                  df['coarse_fine_aggregate'].str.split('[;,_]', expand=True)
                   .rename(columns={0: 'coarse_aggregate', 1: 'fine_aggregate'})], axis=1)
         .astype(float)
      )


输出量:

cement  water  coarse_aggregate  fine_aggregate
0     200.0  159.2            1043.6           771.9
1     200.0  192.0             965.4           806.2
2     446.0  162.0             967.0           712.0
3     380.0  158.0             903.0           768.0
4     141.0  173.5             882.6           785.3
..      ...    ...               ...             ...
222   200.0  192.0             965.4           806.2
223   270.0  160.6             973.9           875.6
224   150.0  185.7            1040.6           734.3
225   330.0  174.9             944.7           755.8
226   288.0  177.4             907.9           829.5

[227 rows x 4 columns]

相关问题