2015-09-08 7 views
7

मैं पांडा dataframe में निम्न डेटा:

state  1st  2nd    3rd 
0 California $11,593,820 $109,264,246 $8,496,273 
1 New York $10,861,680 $45,336,041  $6,317,300 
2 Florida  $7,942,848 $69,369,589  $4,697,244 
3 Texas  $7,536,817 $61,830,712  $5,736,941 

मैं तीन कॉलम (1st, 2nd साथ कुछ सरल विश्लेषण (जैसे, योग, GroupBy) निष्पादित करना चाहते हैं, तीसरा), लेकिन उन तीन स्तंभों का डेटा प्रकार ऑब्जेक्ट (या स्ट्रिंग) है। डॉलर चिह्न के कारण,

data = data.convert_objects(convert_numeric=True) 

लेकिन, रूपांतरण काम नहीं करता है, शायद:

तो मैं डेटा रूपांतरण के लिए निम्न कोड का इस्तेमाल किया। कोई उपाय?

+0

http://stackoverflow.com/questions/27534746/importing-financial-data -इंटो-पायथन-पांडा-उपयोग-पढ़-सीएसवी –

+1

रेगेक्स समाधान के लिए, http://stackoverflow.com/a/31521773/3651127 देखें – dagrha

उत्तर

12

@ एडचम का जवाब चालाक और बदतर है केएस अच्छी तरह से। लेकिन चूंकि एक केक सेंकने के एक से अधिक तरीके हैं .... Regex का उपयोग क्यों नहीं करें? उदाहरण के लिए:

df[df.columns[1:]].replace('[\$,]', '', regex=True).astype(float) 

मेरे लिए, यह थोड़ा और अधिक पठनीय है।

0

आप अवांछित पात्रों को बदलने के लिए vectorised str तरीकों का उपयोग कर सकते हैं और उसके बाद प्रकार डाली int करने के लिए:

In [81]: 
df[df.columns[1:]] = df[df.columns[1:]].apply(lambda x: x.str.replace('$','')).apply(lambda x: x.str.replace(',','')).astype(np.int64) 
df 

Out[81]: 
      state  1st  2nd  3rd 
index           
0  California 11593820 109264246 8496273 
1  New York 10861680 45336041 6317300 
2   Florida 7942848 69369589 4697244 
3   Texas 7536817 61830712 5736941 

dtype परिवर्तन अब पुष्टि की है:

In [82]: 

df.info() 
<class 'pandas.core.frame.DataFrame'> 
Int64Index: 4 entries, 0 to 3 
Data columns (total 4 columns): 
state 4 non-null object 
1st  4 non-null int64 
2nd  4 non-null int64 
3rd  4 non-null int64 
dtypes: int64(3), object(1) 
memory usage: 160.0+ bytes 

एक और तरीका है:

In [108]: 

df[df.columns[1:]] = df[df.columns[1:]].apply(lambda x: x.str[1:].str.split(',').str.join('')).astype(np.int64) 
df 
Out[108]: 
      state  1st  2nd  3rd 
index           
0  California 11593820 109264246 8496273 
1  New York 10861680 45336041 6317300 
2   Florida 7942848 69369589 4697244 
3   Texas 7536817 61830712 5736941 
1

तुम भी locale के रूप में इस प्रकार है

import locale 
import pandas as pd 
locale.setlocale(locale.LC_ALL,'') 
df['1st']=df.1st.map(lambda x: locale.atof(x.strip('$'))) 

नोट उपरोक्त कोड अजगर 3 में परीक्षण किया गया था और Windows वातावरण का उपयोग कर सकते

संबंधित मुद्दे