如何读取一列并对每个单元格应用函数作为元组?

huangapple go评论105阅读模式
英文:

How to read a column and apply a function to each cell as a tuple?

问题

  1. df = [(0,23),(1,22),(4,39),(3,15)]
  2. listing = list(range(0, 24))
  3. def classify_coordinates(coord):
  4. if coord[0] in listing:
  5. return "East"
  6. elif coord[1] in range(28, 41):
  7. return "North"
  8. df_result = [(classify_coordinates(coord), classify_coordinates(coord)) for coord in df]
  9. df1 = pd.DataFrame(df_result, columns=["Comienza calle", "Ubicación comienzo"])
  10. print(df1)
英文:

I'm trying to analyze a database with coordinates (X,Y). I need to read each data in that column and classify it as either North or South if it's "Y" or East or West if it's "X". So basically what I want to do is read each data in that column and apply one of those values depending on the coordinate X and Y.

my df is something like this (it's and xlsx doc but ill try to make something alike)

  1. df = [(0,23),(1,22),(4,39),(3,15)] #so i want to read each coordinate and if X is in a range between 0-23 say its East and if Y is in a range between 28-40 say its North.

I've tried to apply a function to the entire column and later adding a new column to the dataframe with the result from the previous function, I may have the idea but I don't know how to make it.

  1. listing = list(0,23)
  2. def calle():
  3. if calle in listing:
  4. return Oeste #This is the code I tried to make a function with just one of the values
  5. #So basically if the the coordinate is in that range(0-23) I want it to be west
  6. df1["Comienza calle"] = df1["Comienza calle"].apply(calle)
  7. print(df1) #This is how i tried to apply the previous function
  8. #And my idea is to add a new column with the result from that function
  9. df1.insert(2, "Ubicación comienzo", ["Noroeste","Noreste","Suroeste","Sureste"], True)
  10. print(df1)

答案1

得分: 1

你可以通过使用pandas DataFrame或Series对象的apply方法,将一个函数应用于列中元组的每个单元格来实现你在代码中尝试实现的目标。

为了帮助你实现将每个坐标分类为北、南、东或西的目标,以下是一些示例代码:

  1. import pandas as pd
  2. class_ranges = {'X': [(0, 11.5, 'West'), (11.5, 23, 'East')],
  3. 'Y': [(0, 28, 'South'), (28, 40, 'North')]}
  4. def classify_coordinate(coord, coord_type):
  5. for (lower, upper, direction) in class_ranges[coord_type]:
  6. if lower <= coord <= upper:
  7. return direction
  8. return None
  9. df = pd.read_excel('coordinates.xlsx')
  10. df['X Direction'] = df['X'].apply(lambda x: classify_coordinate(x, 'X'))
  11. df['Y Direction'] = df['Y'].apply(lambda y: classify_coordinate(y, 'Y'))
  12. print(df)

希望这对你有所帮助。

英文:

You may do what you were attempting to achieve in your code by using the apply method of a pandas DataFrame or Series object to apply a function to each cell in a column of tuples.

To assist you accomplish your aim of categorising each coordinate as North, South, East, or West, here is some sample code:

  1. import pandas as pd
  2. class_ranges = {&#39;X&#39;: [(0, 11.5, &#39;West&#39;), (11.5, 23, &#39;East&#39;)],
  3. &#39;Y&#39;: [(0, 28, &#39;South&#39;), (28, 40, &#39;North&#39;)]}
  4. def classify_coordinate(coord, coord_type):
  5. for (lower, upper, direction) in class_ranges[coord_type]:
  6. if lower &lt;= coord &lt;= upper:
  7. return direction
  8. return None
  9. df = pd.read_excel(&#39;coordinates.xlsx&#39;)
  10. df[&#39;X Direction&#39;] = df[&#39;X&#39;].apply(lambda x: classify_coordinate(x, &#39;X&#39;))
  11. df[&#39;Y Direction&#39;] = df[&#39;Y&#39;].apply(lambda y: classify_coordinate(y, &#39;Y&#39;))
  12. print(df)

答案2

得分: 1

  1. import pandas as pd
  2. # 在 apply() 中仍然可以使用 apply 调用和一个单独的函数,参见下面的调整后的代码:
  3. # 我们将在 apply() 中使用的函数
  4. def coord_to_text(coord):
  5. x = coord[0]
  6. y = coord[1]
  7. # 修改下面的代码以符合您的期望
  8. if x == 0:
  9. return "东方"
  10. else:
  11. return "北方"
  12. # 使用您的值创建数据框,但在名为 "coords" 的列中
  13. df = pd.DataFrame({"coords": [(0,23),(1,22),(4,39),(3,15)]})
  14. # 将函数应用于 coords 列,并将结果存储在名为 text 的新列中
  15. df["text"] = df["coords"].apply(coord_to_text)
  16. 结果
  17. coords text
  18. 0 (0, 23) 东方
  19. 1 (1, 22) 北方
  20. 2 (4, 39) 北方
  21. 3 (3, 15) 北方
英文:

You can still use the apply call and a separate function, see adjusted code below:

  1. import pandas as pd
  2. # Function that we are going to use in the apply()
  3. def coord_to_text(coord):
  4. x = coord[0]
  5. y = coord[1]
  6. # Fix the code below to match your expectations
  7. if x == 0:
  8. return &quot;East&quot;
  9. else:
  10. return &quot;North&quot;
  11. # Create the dataframe using your values, but in a column named &quot;coords&quot;
  12. df = pd.DataFrame({&quot;coords&quot;: [(0,23),(1,22),(4,39),(3,15)]})
  13. # Apply the funcion to the coords column, store results in a new column named text
  14. df[&quot;text&quot;] = df[&quot;coords&quot;].apply(coord_to_text)

Result:

  1. coords text
  2. 0 (0, 23) East
  3. 1 (1, 22) North
  4. 2 (4, 39) North
  5. 3 (3, 15) North

Again, you need to adjust the function to return the text as you wish it to be

huangapple
  • 本文由 发表于 2023年5月10日 23:00:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219962.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定