我想将 2 个具有整数的列值与它们之间的“_”组合起来,并将其设置为我的输出数据集的索引列。 'ID' 将是我的索引。
示例数据:
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)
预期输出:
将索引和列转换为字符串并通过_
连接,也是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
我是一名优秀的程序员,十分优秀!