如何将对象列转换为字符串并使用替换?

2024-05-01 11:03:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些列['subject', 'H.period', 'DD.period.t']等,实际上所有的列都是对象类型。你知道吗

enter image description here

dtype printscreen

如何将这些列转换为字符串类型?你知道吗

如何使用.replace将csv文件中的“,”转换为“.”?我需要在机器学习算法中使用这些数据。你知道吗


Tags: 文件csv数据对象字符串算法机器类型
2条回答

尽管dtype确实是“object”,但当将type()函数单独应用于列标签时,您会发现它们实际上属于类“str”。 所以这很好。你知道吗

关于你关于替换的问题,我建议如下:

length = len(df[df.columns[0]])
for column in df.columns:
     for index in range(length):
          df[column][index] = df[column][index].replace(",",".")

pandas中没有字符串dtype。如docs中所述:

Note When working with heterogeneous data, the dtype of the resulting ndarray will be chosen to accommodate all of the data involved. For example, if strings are involved, the result will be of object dtype. If there are only floats and integers, the resulting array will be of float dtype.

至于在整个数据帧中用,替换.,请用replace替换regex = True

df = df.replace(',','.',regex=True)
# or
df.replace(',','.',regex=True, inplace = True)

例如:如果您的数据帧df看起来像:

>>> df
  col1         col2
0  x,x    blah,blah
1  y,z  hello,world
2  z.z       ,.,.,.

然后:

df = df.replace(',','.',regex=True)
>>> df
  col1         col2
0  x.x    blah.blah
1  y.z  hello.world
2  z.z       ......

相关问题 更多 >