根据其他变量的某些条件在字符串上添加尾随字符?

时间:2015-03-26 17:56:12

标签: python-2.7 loops pandas

我试图通过Python Pandas操纵数据。但是,我不太清楚如何做到这一点。

想象一下,我有名称数据,每个名称都有相应的字符串长度。我想创建一个新的名称变量,在其中我用“?”填充当前名称变量直到它总共有15个字符。

例如: 迈克米勒将被改装成迈克#miller ????和 G我乔将被转换为g#i#joe ?????????

看来下面这一行:frame3 [“name_filled”] = frame3 [“name”] +填充*“???”是不对的,但我不确定如何根据另外两个变量在一行内迭代。

import pandas as pd
from pandas import DataFrame
import re

# Get csv file into data frame
data = pd.read_csv("C:\Users\KubiK\Desktop\OddNames_sampleData.csv")
frame = DataFrame(data)
frame.columns = ["name", "ethnicity"]
name = frame.name
ethnicity = frame.ethnicity

# Remove missing ethnicity data cases
index_missEthnic = frame.ethnicity.isnull()
index_missName = frame.name.isnull()
frame2 = frame.loc[~index_missEthnic, :]
frame3 = frame2.loc[~index_missName, :]

# Make all letters into lowercase
frame3.loc[:, "name"] = frame3["name"].str.lower()
frame3.loc[:, "ethnicity"] = frame3["ethnicity"].str.lower()

# Remove all non-alphabetical characters in Name
frame3.loc[:, "name"] = frame3["name"].str.replace(r'[^a-zA-Z\s\-]', '') # Retain space and hyphen

# Replace empty space as "#"
frame3.loc[:, "name"] = frame3["name"].str.replace('[\s]', '#')

# Find the longest name in the dataset
frame3["name_length"] = frame3["name"].str.len()
nameLength = frame3.name_length
frame3["filler"] = 15 - nameLength
filler = frame3.filler

# Add "?" to fill spaces up to 15 characters
frame3["name_filled"] = frame3["name"] + filler*"???"

# Test outputs
print frame3

1 个答案:

答案 0 :(得分:2)

使用向量化str方法pad

In [2]:

df = pd.DataFrame({'a':['asdasd','Fred','Ginger']})
df
Out[2]:
        a
0  asdasd
1    Fred
2  Ginger
In [6]:

df.a.str.pad(side='right',width=15,fillchar='?')
Out[6]:
0    asdasd?????????
1    Fred???????????
2    Ginger?????????
Name: a, dtype: object