简体   繁体   English

生成有序 XY 坐标

[英]Generating Ordered XY Coordinates

I'm writetwo python dataframe columns so that two coordinates, X and Y, will increment down their respective columns.我正在写两个 python dataframe 列,这样两个坐标 X 和 Y 将向下递增它们各自的列。 For example:例如:

|  X  |  Y  |
|:----|----:|
|  0  |  0  |
|  0  |  1  |
|  0  |  2  |
|  0  |  3  |
|  0  |  4  |
|  1  |  0  |
|  1  |  1  |
|  1  |  2  |
|  1  |  3  |
|  1  |  4  |
|  2  |  0  |
|  2  |  1  |
|  2  |  2  |
|  2  |  3  |
|  2  |  4  |
| ... | ... |

Any ideas how to generate these columns?任何想法如何生成这些列?

You can generate dictionary with iteration and then create DataFrame from that you can check below sample for that;您可以通过迭代生成字典,然后从中创建 DataFrame 您可以检查以下示例;

import pandas as pd

my_df = []
for i in range(0,10):
    d = {
        'x' : i,  # some formula for obtaining values
        'y' : i*2,

    }
    my_df.append(d)

my_df = pd.DataFrame(my_df)
print(my_df)

To generate values you require you need to fiddle with iteration.要生成您需要的值,您需要摆弄迭代。 Leaving up to you:).留给你:)。 Logic would be this, you need to add (0,1,2,3,4) values to y column, so you can get modulo each iteration and add accordingly.逻辑是这样的,您需要将 (0,1,2,3,4) 值添加到 y 列,因此您可以在每次迭代中取模并相应地添加。 For x column you need to +1 to x value after each 4th iteration.对于 x 列,您需要在每 4 次迭代后 +1 到 x 值。

Just use range() and a list comprehension (modify the 3 if you want another length):只需使用range()列表理解(如果您想要另一个长度,请修改3 ):

df = pd.DataFrame(
    [[n, m] for n in range(3) for m in range(5)],
    columns=["X", "Y"]
)

Result:结果:

    X  Y
0   0  0
1   0  1
2   0  2
3   0  3
4   0  4
5   1  0
6   1  1
7   1  2
8   1  3
9   1  4
10  2  0
11  2  1
12  2  2
13  2  3
14  2  4

Or use itertools.product to get the same result:或使用itertools.product获得相同的结果:

from itertools import product

df = pd.DataFrame(product(range(3), range(5)), columns=["X", "Y"])

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

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