gpt4 book ai didi

python - 如何在python中组合两个整数列

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:35 25 4
gpt4 key购买 nike

我想将 2 个具有整数的列值与它们之间的“_”组合起来,并将其设置为我的输出数据集的索引列。 'ID' 将是我的索引。

示例数据:

inp

import pandas as pd
import numpy as np
import io

data = '''
ID,Ang,1
23,0,0.88905321
23,10,0.962773412
23,20,1.004187813
23,30,1.008301223
105,0,0.334209544
105,10,0.39043363
105,20,0.434241204
105,30,0.460348427
47,0,0.020669404
47,10,0.032299446
47,20,0.050602654
47,30,0.073371391
'''
df = pd.read_csv(io.StringIO(data),index_col=0)

预期输出:

out

最佳答案

将索引和列转换为字符串并通过_连接,也是DataFrame.pop用于提取列,因此 drop 不是必需的:

df.index = df.index.astype(str) + '_' + df.pop('Ang').astype(str)

或者使用DataFrame.set_index :

df = df.set_index(df.index.astype(str) + '_' + df.pop('Ang').astype(str))

print (df)
1
23_0 0.889053
23_10 0.962773
23_20 1.004188
23_30 1.008301
105_0 0.334210
105_10 0.390434
105_20 0.434241
105_30 0.460348
47_0 0.020669
47_10 0.032299
47_20 0.050603
47_30 0.073371

如果还想索引名称 ID 设置 df.index.name:

df.index = df.index.astype(str) + df.pop('Ang').astype(str)
df.index.name = 'ID'

第二个解决方案使用DataFrame.rename_axis :

df = (df.set_index(df.index.astype(str) + '_' + df.pop('Ang').astype(str))
.rename_axis('ID'))
print (df)
1
ID
23_0 0.889053
23_10 0.962773
23_20 1.004188
23_30 1.008301
105_0 0.334210
105_10 0.390434
105_20 0.434241
105_30 0.460348
47_0 0.020669
47_10 0.032299
47_20 0.050603
47_30 0.073371

编辑:

如果有 .0 值的 float ,首先尝试转换为整数:

df.index = (df.index.astype('int').astype(str) + '_' + 
df.pop('Ang').astype('int').astype(str))

如果无法转换为整数,则一个可能的原因是缺少值:

print (df)
Ang 1
ID
23.0 0.0 0.889053
23.0 10.0 0.962773
23.0 20.0 1.004188
23.0 30.0 1.008301
105.0 0.0 0.334210
105.0 10.0 0.390434
105.0 20.0 0.434241
105.0 30.0 0.460348
47.0 NaN 0.020669
NaN 10.0 0.032299
47.0 20.0 0.050603
NaN NaN 0.073371

Pandas 0.24+ 的一种可能解决方案是使用 integer na通过转换为 Int64:

df.index = (df.index.astype('Int64').astype(str) + '_' + 
df.pop('Ang').astype('Int64').astype(str))

print (df)
1
23_0 0.889053
23_10 0.962773
23_20 1.004188
23_30 1.008301
105_0 0.334210
105_10 0.390434
105_20 0.434241
105_30 0.460348
47_nan 0.020669
nan_10 0.032299
47_20 0.050603
nan_nan 0.073371

或者将缺失值替换为一些整数,例如-1 然后将所有值转换为整数:

df.index = (df.index.fillna(-1).astype('int').astype(str) + '_' + 
df.pop('Ang').fillna(-1).astype('int').astype(str))

print (df)
1
23_0 0.889053
23_10 0.962773
23_20 1.004188
23_30 1.008301
105_0 0.334210
105_10 0.390434
105_20 0.434241
105_30 0.460348
47_-1 0.020669
-1_10 0.032299
47_20 0.050603
-1_-1 0.073371

关于python - 如何在python中组合两个整数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58571840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com