我正在尝试在数据框的左侧添加一列。默认情况下,它似乎添加到右侧。有没有办法在左侧添加列?
这是我的代码:
import pandas as pd
import numpy as np
df = pd.read_csv("/home/Sample Text Files/sample5.csv", delimiter = "\t")
df=pd.DataFrame(df)
df['Creation_DT']=pd.to_datetime('today')
print(df)
以下是输出:
ID,Name,Age Creation_DT
0 1233,Maliva,15 2019-07-17 11:11:37.145194
我希望输出如下:
Creation_DT, ID, Name, Age
[value], [Value], [Value], [Value]
答案 0 :(得分:1)
您可以添加一行代码来重新排列列,如下所示:
import re
imports pandas as pd
# my df has these columns, wehre body contains the email chains
df = pd.DataFrame(columns=['thread_id', 'body', 'from', 'message_sent_date'])
example_id = 1
email1 = df.iloc[example_id]['body']
email_stripped = strip_html(email1)
email_stripped = email_stripped.replace('>', '')
from_name1 = df.iloc[example_id]['from_name']
from_email_address = df.iloc[example_id]['from']
match_on_date_intro2 = "On [^\n\r]* wrote:"
match_on_email_intro = 'From: ' + from_name1 + ' <' + from_email_address
match_original_msg = '--Original Message--'
regex_to_match = ('('
#+ match_on_date_intro
#+ '|'
+ match_on_email_intro
+ '|'
+ match_on_date_intro2
+ '|'
+ match_original_msg
+ ')'
)
l = re.compile(regex_to_match).split(email_stripped)
print("<<<<<<============= MESSAGE STARTING =========>>>>>>")
for x in l:
print("============= NEXT MESSAGE =========")
print(x)
另一个选择是在转换期间插入列:
df = df[['Creation_DT', 'ID', 'Name', 'Age']]
答案 1 :(得分:1)
尝试df.insert将列放置在特定数据上
df.insert(loc=0, column='Creation_DT', value=pd.to_datetime('today'))