【发布时间】:2017-04-27 21:08:56
【问题描述】:
我有一个看起来像这样的 pandas 数据框:
ID1 ID2 Len1 Date1 Type1 Len2 Date2 Type2 Len_Diff Date_Diff Score
123 456 1-Apr M 6-Apr L
234 567 20-Apr S 19-Apr S
345 678 10-Apr M 1-Jan M
我想通过从数据集中计算来填充 Len1、Len2、Len_Diff 和 Date_Diff 列。每个 ID 对应一个文本文件,可以使用 get_text 函数检索其文本,并且可以计算该文本的长度
到目前为止,我的代码可以为每一列单独执行此操作:
def len_text(key):
text = get_text(key)
return len(text)
df['Len1'] = df['ID1'].map(len_text)
df['Len2'] = df['ID2'].map(len_text)
df['Len_Diff'] = (abs(df['Len1'] - df['Len2']))
df['Date_Diff'] = (abs(df['Date1'] - df['Date2']))
df['Same_Type'] = np.where(df['Type1']==df['Type2'],1,0)
如何一步将所有这些列添加到数据框中。我希望它们一步到位,因为我想将代码包装在 try/except 块中,以克服因无法解码文本而导致的值错误。
try:
<code to add all five columns at once>
except ValueError:
print "Failed to decode"
在上面的每一行中添加一个 try/except 块会使它变得丑陋。
还有其他问题,例如:Changing certain values in multiple columns of a pandas DataFrame at once,处理多列,但它们都在谈论影响多列的一个计算/更改。我想要的是不同的计算来添加不同的列。
更新:从下面给出的答案中,我尝试了两种不同的方法来解决这个问题,到目前为止 部分 运气。这是我所做的:
方法 1:
# Add calculated columns Len1, Len2, Len_Diff, Date_Diff and Same_Type
def len_text(key):
try:
text = get_text(key)
return len(text)
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError, requests.exceptions.Timeout, ValueError) as e:
return 0
df.loc[:, ['Len1','Len2','Len_Diff','Date_Diff','Same_Type']] = pd.DataFrame([
df['ID1'].map(len_text),
df['ID2'].map(len_text),
np.abs(df['ID1'].map(len_text) - df['ID2'].map(len_text)),
np.abs(df['Date1']- df['Date2'])
np.where(df['Type1']==df['Type2'],1,0)
])
print df.info()
结果1:
<class 'pandas.core.frame.DataFrame'> RangeIndex: 570 entries, 0 to 569 df columns (total 10 columns): ID1 570 non-null int64 Date1 570 non-null int64 Type1 566 non-null object Len1 0 non-null float64 ID2 570 non-null int64 Date2 570 non-null int64 Type2 570 non-null object Len2 0 non-null float64 Date_Diff 0 non-null float64 Len_Diff 0 non-null float64 dtypes: float64(4), int64(4), object(2) memory usage: 58.0+ KB None
方法2:
def len_text(col):
try:
return col.map(get_text).str.len()
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError, requests.exceptions.Timeout, ValueError) as e:
return 0
formulas = """
Len1 = @len_text(ID1)
Len2 = @len_text(ID2)
Len_Diff = Len1 - Len2
Len_Diff = Len_Diff.abs()
Same_Type = (Type1 == Type2) * 1
"""
try:
df.eval(formulas, inplace=True, engine='python')
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError, requests.exceptions.Timeout, ValueError) as e:
print e
print df.info()
结果2:
"__pd_eval_local_len_text" is not a supported function <class 'pandas.core.frame.DataFrame'> RangeIndex: 570 entries, 0 to 569 df columns (total 7 columns): ID1 570 non-null int64 Date1 570 non-null int64 Type1 566 non-null object ID2 570 non-null int64 Date2 570 non-null int64 Type2 570 non-null object Len1 570 non-null int64 dtypes: int64(5), object(2) memory usage: 31.2+ KB None /Users/.../anaconda2/lib/python2.7/site-packages/pandas/computation/eval.py:289: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy target[parsed_expr.assigner] = ret
【问题讨论】:
-
为什么不把所有五行放在同一个try/except中?
-
@Jerome,我试过了。当我这样做时,只有第一列被填充。
标签: python pandas dataframe httprequest text-analysis