Python Pandas获取列值的前几位数字

7

我需要获取数据框每行的另一个索引(或重置索引后的列)中存储的数字的前两位。我该怎么做?

我的数据框:

        value
index1       
110202      1
223168      5
850484      2
298008      3
950000      6
113500      6
849464      2
849616     10

我希望获取以下内容,例如:
                  value
index1 new_value       
110202 11             1
223168 22             5
850484 85             2
298008 29             3
950000 95             6
113500 11             6
849464 84             2
849616 84            10
2个回答

11

假设 index1df 的索引,您可以执行以下操作:

df['new_value'] = df.index.astype(str).str[:2]
print(df)

输出

        value new_value
index1                 
110202      1        11
223168      5        22
850484      2        85
298008      3        29
950000      6        95
113500      6        11
849464      2        84
849616     10        84

将该列转换为字符串列,然后使用str访问器来获取前两个字符。有关文本数据处理的更多信息,请参见此处

作为替代方案,您可以重置索引并访问 index1 列,例如:

df = df.reset_index()
df['new_value'] = df['index1'].astype(str).str[:2]
print(df.set_index(['index1', 'new_value']))

输出

                  value
index1 new_value       
110202 11             1
223168 22             5
850484 85             2
298008 29             3
950000 95             6
113500 11             6
849464 84             2
849616 84            10

请注意,在这个替代方案中,我将索引设置为列 new_valueindex1

谢谢,但我遇到了以下错误:TypeError: 设置 <class 'pandas.core.index.MultiIndex'> 的 dtype 为除 object 以外的任何类型都不支持。 - user9187374
@user9187374 已更新答案,请告知备选方案是否可行。 - Dani Mesejo

1
从df.index.values创建一个列表,然后迭代该数组中的值并获取前2个字符。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接