将dataframe索引转换为字符串和子字符串?

时间:2017-04-13 18:40:09

标签: pandas dataframe

想知道最简单的方法是将下面的数据帧索引拆分为子字符串,并将第二部分设置为新数据帧中的列。

Input:
          Ask    Bid   Last Open_Int Vol
245.0P  11.36  11.15  10.41       37  30
225.0C  10.31  10.23   10.3       52   5
224.5C  10.78  10.67     12       72  72
223.5C  11.68  11.56  12.68       89  59
244.5P  10.83  10.64   8.65      118  22
244.0P  10.34  10.15   9.93      137  10

Output:
          Ask    Bid   Last Open_Int Vol Type
245.0P  11.36  11.15  10.41       37  30 P
225.0C  10.31  10.23   10.3       52   5 C
224.5C  10.78  10.67     12       72  72 C
223.5C  11.68  11.56  12.68       89  59 C
244.5P  10.83  10.64   8.65      118  22 P
244.0P  10.34  10.15   9.93      137  10 P

3 个答案:

答案 0 :(得分:5)

df.assign(Type=df.index.str[-1])

          Ask    Bid   Last  Open_Int  Vol Type
245.0P  11.36  11.15  10.41        37   30    P
225.0C  10.31  10.23  10.30        52    5    C
224.5C  10.78  10.67  12.00        72   72    C
223.5C  11.68  11.56  12.68        89   59    C
244.5P  10.83  10.64   8.65       118   22    P
244.0P  10.34  10.15   9.93       137   10    P

答案 1 :(得分:2)

对于您的示例,这是解决方案:

df['type'] = df.index.str[-1]

答案 2 :(得分:0)

如果您的索引是一致的,那么这是解决此问题的直接方法 -- SOMETHING FROM ADVENTURE WORKS THIS WORKS AS THE ABOVE POSTER --- USING 'WITH CTE AS' -- MY ANSWER TO A QUERY WITH CTE AS ( SELECT HE.Gender AS [GENDER], HE.HireDate AS [HIREDATE], HE.BirthDate AS [BIRTHDATE], CASE WHEN DATEPART(YY,[BIRTHDATE]) BETWEEN 1962 AND 1970 AND [GENDER] = 'M' AND DATEPART(YY,[HIREDATE]) > 2001 THEN 'MALE' WHEN DATEPART(YY,[BIRTHDATE]) BETWEEN 1972 AND 1975 AND [GENDER] = 'F' AND DATEPART(YY,[HIREDATE]) BETWEEN 2001 AND 2002 THEN 'FEMALE' ELSE 'NOTREQUIRED' END AS [RESULT] FROM [HumanResources].[Employee] AS HE ) SELECT * FROM CTE WHERE [RESULT] <> 'NOTREQUIRED' -- GOT THIS TOO WORK NO FEMALES IN RESULT ORDER BY [RESULT]