我在单个数据框中有以下数据,我从XML
解析$.when
我喜欢在“\ n”列之后创建每一行,并且与列关联的值是下一行,例如:
function getFechas(val) {
// return promise
return $.ajax({
type: "POST",
url: '...',
data: {....}
}).then(function(resp) {
// return processed data to next then() in chain
var venc = resp.map(function(item) {
return item.fecha_vencimiento
});
return venc;
});
}
$.when(getFechas( /*datepickerValue*/ )).done(function(venc) {
console.log(venc);
}).fail(function(err){
console.log('Request failed');
});
这样做是否有更优雅的方式: 对于doc_df.itertuples()中的行: 并遍历每一行并解析?
答案 0 :(得分:4)
import pandas as pd
import numpy as np
# set dataframe
...
# get columns name
columns = []
count_n = 0
for i in range(0, len(df)-1):
if (df.iloc[i]['xml_data'] == '\\n'):
columns.append(df.iloc[i+1]['xml_data'])
count_n += 1
# generate new df
new_df = pd.DataFrame(columns = columns, index = np.arange(count_n))
j = 0
count = 0
# set values
for i in range(0, len(df)-2):
if (df.iloc[i]['xml_data'] == '\\n'):
new_df.iloc[j][df.iloc[i+1]['xml_data']] = df.iloc[i+2]['xml_data']
count += 1
if count == len(new_df):
count = 0
j += 1
new_df.dropna(inplace=True)
print(new_df)
结果:
sessionKey Number CreateDate Id customerAge
0 JKX6G3_07092016_1476953673631 JKX6G3 1468040400000 83737626 64
答案 1 :(得分:4)
我要查找\n
的位置,然后添加一个来定位键,并为值添加2。然后构建一个数组和一个后续的数据帧
v = df.xml_data.values
a, b = np.where(v == '\\n')[0][None, :] + [[1], [2]]
pd.DataFrame([v[b]], columns=v[a])
sessionKey Number CreateDate Id customerAge
0 JKX6G3_07092016_1476953673631 JKX6G3 1468040400000 83737626 64