用整数在Python中编写一个循环

发布于 2025-02-05 13:24:20 字数 850 浏览 2 评论 0原文

我有一个数据框架:

data = [[0xD8E3ED, 2043441], [0xF7F4EB, 912788],[0x000000,6169]]
df = pd.DataFrame(data, columns=['c_code', 'occurence'])

“

我正在尝试循环循环C_Code以获取整数值。以下代码可以获取整数,

hex_val = '0xFF9B3B'
print(int(hex_val, 0))

16751419

但是当我尝试循环浏览列时,我会遇到问题。我目前有此运行,但我只是在覆盖每个值。

for i in range(len(df)):
    df['value'] = int((df['c_code'].iloc[i]), 0)

理想的输出将是一个具有反映C_CODE值的值列的DF。下图显示了所需的格式,但请注意,所有行的值都是相同的。我相信我需要附加行,但我不确定如何做

”在此处输入图像描述”

I have a dataframe as such:

data = [[0xD8E3ED, 2043441], [0xF7F4EB, 912788],[0x000000,6169]]
df = pd.DataFrame(data, columns=['c_code', 'occurence'])

df

I am attempting to loop through c_code to get an integer value. The following code works to obtain the integer

hex_val = '0xFF9B3B'
print(int(hex_val, 0))

16751419

But when I try to loop through the column I run into an issue. I currently have this running but am just overwriting every value.

for i in range(len(df)):
    df['value'] = int((df['c_code'].iloc[i]), 0)

Ideal output would be a df with a value column that reflects the value of the c_code. The image below shows the desired format but notice that the value is the same for all rows. I believe that I need to append rows but I am unsure of how to do that

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅浅淡淡 2025-02-12 13:24:20

我相信您可以修改列C_Code的类型,并将其分配给新列。

import pandas as pd

data = [['0xD8E3ED', 2043441], ['0xF7F4EB', 912788],['0x000000',6169]]
df = pd.DataFrame(data, columns=['c_code', 'occurence'])
df['value'] = df['c_code'].apply(int, base=16)

另外,我不得不将十六进制的数字作为字符串,即使不是熊猫会直接将它们转换为int。

我得到了这个结果:

I believe that you can modify the type of your column c_code and assign this to a new column.

import pandas as pd

data = [['0xD8E3ED', 2043441], ['0xF7F4EB', 912788],['0x000000',6169]]
df = pd.DataFrame(data, columns=['c_code', 'occurence'])
df['value'] = df['c_code'].apply(int, base=16)

Also, I had to put the hexadecimal numbers as strings, if not pandas converts them to int directly.

I get this result:
enter image description here

不离久伴 2025-02-12 13:24:20

您将整列分配给循环中每个步骤的新值,

df["value"] = ...

指定一行,需要将其更改为df [“ value”] [i] = ...

以 必须循环遍历熊猫中的每个值。

尝试:

df["value"] = int(df["c_code"], 0)

You are assigning the entire column to a new value at each step in the loop

df["value"] = ...

To specify a row you need to change it to df["value"][i] = ...

However, You shouldn't have to loop through each value in Pandas.

try:

df["value"] = int(df["c_code"], 0)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文