簡體   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