Pandas切片字符串与另一列的索引

时间:2017-06-10 04:28:31

标签: python pandas

我想使用另一列的索引来切割此字符串。我得到NaN而不是字符串片段。

import pandas as pd
from pandas import DataFrame, Series

sales = {'name': ['MSFTCA', 'GTX', 'MSFTUSA', ],
         'n_chars': [2, 2, 3],
         'Jan': [150, 200, 50],
         'Feb': [200, 210, 90],
         'Mar': [140, 215, 95]}
df = pd.DataFrame.from_dict(sales)
df

def extract_location(name, n_chars):
    return( name.str[-n_chars:])

df.assign(location=(lambda x: extract_location(x['name'], x['n_chars']))).to_dict()

给出:

{'Feb': {0: 200, 1: 210, 2: 90},
 'Jan': {0: 150, 1: 200, 2: 50},
 'Mar': {0: 140, 1: 215, 2: 95},
 'location': {0: nan, 1: nan, 2: nan},
 'n_chars': {0: 2, 1: 2, 2: 3},
 'name': {0: 'MSFTCA', 1: 'GTX', 2: 'MSFTUSA'}}

2 个答案:

答案 0 :(得分:3)

您需要使用apply axis=1按行处理:

def extract_location(name, n_chars):
    return( name[-n_chars:])


df=df.assign(location=df.apply(lambda x: extract_location(x['name'], x['n_chars']), axis=1))
print (df) 
   Feb  Jan  Mar  n_chars     name location
0  200  150  140        2   MSFTCA       CA
1  210  200  215        2      GTX       TX
2   90   50   95        3  MSFTUSA      USA
df = df.assign(location=df.apply(lambda x: x['name'][-x['n_chars']:], axis=1))
print (df) 
   Feb  Jan  Mar  n_chars     name location
0  200  150  140        2   MSFTCA       CA
1  210  200  215        2      GTX       TX
2   90   50   95        3  MSFTUSA      USA

答案 1 :(得分:3)

使用理解

df.assign(location=[name[-n:] for n, name in zip(df.n_chars, df.name)])

   Feb  Jan  Mar  n_chars     name location
0  200  150  140        2   MSFTCA       CA
1  210  200  215        2      GTX       TX
2   90   50   95        3  MSFTUSA      USA

你可以用

加快速度
df.assign(location=[name[-n:] for n, name in zip(df.n_chars.values, df.name.values)])