繁体   English   中英

遍历 pandas dataframe 中的列和行并将字符串转换为浮点数

[英]Iterate over columns and rows in a pandas dataframe and convert string to float

我有以下 dataframe:

col1  col2  col3
25,4  34,2  33,2
33,25 30.2  10,2
.................

我想遍历该数据集中的所有列和行。

df_range = len(df)

for column in df:
  for i in range(df_range):
    str.replace(',', '.').astype(float)
    print(df)

我收到以下错误:

TypeError                                 Traceback (most recent call last)

<ipython-input-38-47f6c96d2e67> in <module>()
      3 for column in df2:
      4   for i in range(df_range):
----> 5     str.replace(',', '.').astype(float)
      6 
      7     print(df)

TypeError: replace() takes at least 2 arguments (1 given)

为什么str.replace(',', '.').astype(float)会给你任何有用的东西? 该表达式中没有任何内容涉及您正在迭代的内容。 即使它要在没有错误的情况下评估某些东西,它也会在循环的每次迭代中评估相同的东西。

如果您执行df.loc[i,column].replace(',','.') ,则replace是来自字符串 object df.loc[i,column]的方法,并且需要两个 arguments oldnew 但是,当您执行str.replace(',','.')时, replacestr type中的方法,而不是 string instance中的方法,因此需要 arguments self oldnew 第一个参数','被解释为self ,然后留下'.' old ,没有new的。 当您使用replace时,您必须将原始字符串作为参数提供给它,或者从原始字符串中获取replace方法。

此外,您不应该使用索引遍历df 我们applymap代替。

假设您想在所有行和列中将逗号更改为点,您应该这样做:

df = df.applymap(lambda x: x.replace(',','.')).astype(float)

对于特定列,您可以执行以下操作:

df['col1'] = df['col1'].str.replace(',','.').astype(float)

或者

df['col1'] = df['col1'].map(lambda x: x.replace(',','.')).astype(float)

或者

df['col1'] = df['col1'].apply(lambda x: x.replace(',','.')).astype(float)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM