根据字符串的长度附加

时间:2016-03-22 03:52:13

标签: python pandas python-2.x

我有这样的df:

Year   Month  Day
1984   1      1
1985   12     22

我希望如此MonthDay无论如何都有两位数。所以我想要的数据框是这样的:

Year   Month  Day
1984   01     01
1985   12     22

我一直在玩这个:

for i in df.Month:
    i=str(i)
    if len(i) < 2:
        i='0' + i
    print i

但我不确定如何将新值重新插入到数据框中,我很确定有更好的方法可以在第一时间执行此操作

4 个答案:

答案 0 :(得分:3)

您可以使用astype转换为stringzfill来填充0

#df['Year'] = df['Year'].astype(str) #if column Year has to be string
df['Month'] = df['Month'].astype(str).str.zfill(2)
df['Day'] = df['Day'].astype(str).str.zfill(2)
print df
   Year Month Day
0  1984    01  01
1  1985    12  22

如果所有列中的type必须转换为string

df = df.astype(str) 
df['Month'] = df['Month'].str.zfill(2)
df['Day'] = df['Day'].str.zfill(2)
print df

<强>计时

In [225]: %timeit df1.apply(lambda x: x.astype(str).str.zfill(2), axis=1)
1 loops, best of 3: 500 ms per loop

In [226]: %timeit a(df)
100 loops, best of 3: 10.8 ms per loop

<强>代码

df1 = df.copy()

def a(df):
    df = df.astype(str); 
    df['Month'] = df['Month'].str.zfill(2);
    df['Day'] = df['Day'].str.zfill(2);
    return df

print df1.apply(lambda x: x.astype(str).str.zfill(2), axis=1)
print a(df)

答案 1 :(得分:0)

如果您担心此演示文稿问题,您应该让那些DataFrame保持原样,并且只有当您需要生成报告时才会这样。

然后它成为一般的字符串格式化问题( see also format() )。下面显示的是(1)convert-to-string,(2)padded-to-length-two-with-leading-spaces,(3)padded-to-length-two-with-leading-zero:

>>> ['{}'.format(x) for x in range(10)]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> ['{:2}'.format(x) for x in range(10)]
[' 0', ' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9']
>>> ['{:02}'.format(x) for x in range(10)]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09']

答案 2 :(得分:0)

我认为使用new load(); new Thread(){ public void run(){ try { Thread.sleep(3000); //i think you should call this 2 lines below in main thread dispose(); new gameInfo(); } catch (InterruptedException ex) { Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex); } } }.start(); 创建日期列以使用numpy datetime数据类型可能是个好主意。它实际上看起来会为您提供接近您想要的格式,但您也可以使用to_datetime所需的任何格式从此处格式化日期:

dt.strftime

答案 3 :(得分:0)

请尝试此选项。如果您想要包含2位数的月份和日期。

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
           SSLVerifyClient="optional"
           keystoreFile="tomcat.jks"
           keystoreType="JKS"
           keystorePass="mypass"
           clientAuth="false" sslProtocol="TLS" />
相关问题