用整数在Python中编写一个循环
我有一个数据框架:
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'])
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信您可以修改列C_Code的类型,并将其分配给新列。
另外,我不得不将十六进制的数字作为字符串,即使不是熊猫会直接将它们转换为int。
我得到了这个结果:

I believe that you can modify the type of your column c_code and assign this to a new column.
Also, I had to put the hexadecimal numbers as strings, if not pandas converts them to int directly.
I get this result:

您将整列分配给循环中每个步骤的新值,
指定一行,需要将其更改为
df [“ value”] [i] = ...
以 必须循环遍历熊猫中的每个值。
尝试:
You are assigning the entire column to a new value at each step in the loop
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: