我正在尝试读取和写入数据帧到管道分隔文件.一些字符是非罗马字母(`,ç,ñ等).但是当我尝试将重音写为ASCII时,它就会中断.
df = pd.read_csv('filename.txt',sep='|', encoding='utf-8')
<do stuff>
newdf.to_csv('output.txt', sep='|', index=False, encoding='ascii')
-------
File "<ipython-input-63-ae528ab37b8f>", line 21, in <module>
newdf.to_csv(filename,sep='|',index=False, encoding='ascii')
File "C:\Users\aliceell\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1344, in to_csv
formatter.save()
File "C:\Users\aliceell\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\formats\format.py", line 1551, in save
self._save()
File "C:\Users\aliceell\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\formats\format.py", line 1652, in _save
self._save_chunk(start_i, end_i)
File "C:\Users\aliceell\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\formats\format.py", line 1678, in _save_chunk
lib.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer)
File "pandas\lib.pyx", line 1075, in pandas.lib.write_csv_rows (pandas\lib.c:19767)
UnicodeEncodeError: 'ascii' codec can't encode character '\xb4' in position 7: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
如果我将to_csv改为utf-8编码,那么我无法正确读取该文件:
newdf.to_csv('output.txt',sep='|',index=False,encoding='utf-8')
pd.read_csv('output.txt', sep='|')
> UnicodeDecodeError: …Run Code Online (Sandbox Code Playgroud) 我有一个数据框,我正在尝试对两行求和而不弄乱行的顺序。
> test = {'counts' : pd.Series([10541,4143,736,18,45690], index=['Daylight','Dawn','Other / unknown','Uncoded & errors','Total']), 'percents' : pd.Series([23.07,9.07,1.61,0.04,100], index=['Daylight','Dawn','Other / unknown','Uncoded & errors','Total'])}
> testdf = pd.DataFrame(test)
counts percents
Daylight 10541 23.07
Dawn 4143 9.07
Other / unknown 736 1.61
Uncoded & errors 18 0.04
Total 45690 100.00
Run Code Online (Sandbox Code Playgroud)
我想要这个输出:
counts percents
Daylight 10541 23.07
Dawn 4143 9.07
Other / unknown 754 1.65 <-- sum of 'other/unknown' and 'uncoded & errors'
Total 45690 100.00
Run Code Online (Sandbox Code Playgroud)
这是我所能得到的最接近的结果:
> sum_ = testdf.loc[['Other / unknown', 'Uncoded & errors']].sum().to_frame().transpose() …Run Code Online (Sandbox Code Playgroud) 我有两个要合并的大数据框列表。这是数据的示例。
list1 = list(data.frame(Wvlgth = c(337, 337.5, 338, 338.5, 339, 339.5),
Global = c(".9923+00",".01245+00", ".0005+00", ".33421E+00", ".74361+00", ".129342+00"),
group = c(0,0,0,0,0,0)),
data.frame(Wvlgth = c(337, 337.5, 338, 338.5, 339, 339.5),
Global = c(".1284+00",".0098+00", ".7853+00", ".2311+00", ".1211+00", ".75345+00"),
group = c(1,1,1,1,1,1)))
list2 = list(data.frame(Wvlgth = c(337, 337.5, 338, 339),
time = c("13.445","13.445", "13.445", "13.445"),
IRD = c(.01324, .34565, .92395, .67489)),
data.frame(Wvlgth = c(337, 337.5, 338, 339),
time = c("13.45361","13.45361", "13.45361", "13.45361"),
IRD = c(.20981, .98703, .54092, .38567)))
Run Code Online (Sandbox Code Playgroud)
我想通过“Wvlgth”将 list1 的每个数据帧与 list2 的每个数据帧合并,以获得如下内容: …
我有两个系列。我想从另一个数据帧中减去一个数据帧,即使它们的列数不同。
>df1
index 0 1 2 3 4 5
TOTAL 5 46 56 110 185 629
>df2
index 1 2 3 4 5
Use 25 37 86 151 512
Run Code Online (Sandbox Code Playgroud)
我假设减去具有不同维度的两个数据框只会导致不匹配的列(在这种情况下,列 0)中出现 NaN。其余列将是 df1[1]-df2[1]、df1[2]-df2[2] 等的结果。
>df1 - df2
index 0 1 2 3 4 5
TOTAL NaN 21 19 24 34 117
Run Code Online (Sandbox Code Playgroud)
但这种情况并非如此。当我减去数据帧时会发生这种情况?
>df1 - df2
index 0 1 2 3 4 5
Use NaN NaN NaN NaN NaN NaN
TOTAL NaN NaN NaN NaN NaN NaN
Run Code Online (Sandbox Code Playgroud)
我也试过只减去这些值:
>df1.values …Run Code Online (Sandbox Code Playgroud) 我有一个数据框,其中包含一列我要转换为int的浮点数:
> df['VEHICLE_ID'].head()
0 8659366.0
1 8659368.0
2 8652175.0
3 8652174.0
4 8651488.0
Run Code Online (Sandbox Code Playgroud)
从理论上讲,我应该能够使用:
> df['VEHICLE_ID'] = df['VEHICLE_ID'].astype(int)
Run Code Online (Sandbox Code Playgroud)
但我得到:
Output: ValueError: Cannot convert NA to integer
Run Code Online (Sandbox Code Playgroud)
但我很确定本系列中没有NaN:
> df['VEHICLE_ID'].fillna(999,inplace=True)
> df[df['VEHICLE_ID'] == 999]
> Output: Empty DataFrame
Columns: [VEHICLE_ID]
Index: []
Run Code Online (Sandbox Code Playgroud)
这是怎么回事?
我有一个键和值的字典。我想“映射”数据框列中的数字,其中原始列是键,新列是值。
但是,字典中未包含的任何值都应编码为 999。
原始数据框:
Col1
0 02
1 03
2 02
3 02
4 04
5 88
6 77
Run Code Online (Sandbox Code Playgroud)
字典:
codes = {'01':'05',
'02':'06',
'03':'07',
'04':'08'}
Run Code Online (Sandbox Code Playgroud)
预期输出:
>>> df['ColNew'] = df['Col1'].map(codes)
ColNew
0 06
1 07
2 06
3 06
4 08
5 999
6 999
Run Code Online (Sandbox Code Playgroud)
除了首先在字典中包含 999 代码之外,我不知道该怎么做。当涉及一百多个代码并且其中只有少数需要是 999 以外的任何代码时,这令人沮丧。
我有两列要使用相同的字典映射到单个新列(如果字典中没有匹配的键,则返回 0)。
>> codes = {'2':1,
'31':1,
'88':9,
'99':9}
>> df[['driver_action1','driver_action2']].to_dict()
{'driver_action1': {0: '1',
1: '1',
2: '77',
3: '77',
4: '1',
5: '4',
6: '2',
7: '1',
8: '77',
9: '99'},
'driver_action2': {0: '31',
1: '99',
2: '31',
3: '55',
4: '1',
5: '5',
6: '99',
7: '2',
8: '4',
9: '99'}}
Run Code Online (Sandbox Code Playgroud)
我以为我可以这样做:
>> df['driver_reckless_remapped'] = df[['driver_action1','driver_action2']].applymap(lambda x: codes.get(x,0))
Run Code Online (Sandbox Code Playgroud)
预期输出:
driver_action1 driver_action2 driver_reckless_remapped
0 1 31 1
1 1 99 9
2 77 31 1
3 77 55 0 …Run Code Online (Sandbox Code Playgroud) 我正在尝试提取 XML 文件中特定标签的内容。
XML 示例:
<facts>
<fact>
<name>crash</name>
<full_name>Crash</full_name>
<variables>
<variable>
<name>id</name>
<proper_name>Crash Instance</proper_name>
<type>INT</type>
<interpretation>key</interpretation>
</variable>
<variable>
<name>accident_key</name>
<proper_name>Case Identifier</proper_name>
<interpretation>string</interpretation>
<type>CHAR(9)</type>
</variable>
<variable>
<name>accident_year</name>
<proper_name>Crash Year</proper_name>
<interpretation>dim</interpretation>
<type>INT</type>
</variable>
</variables>
</fact>
<fact>
<name>vehicle</name>
<full_name>Vehicle</full_name>
<variables>
<variable>
<name>id</name>
<proper_name>Vehicle Instance</proper_name>
<type>INT</type>
</variable>
<variable>
<name>crash_id</name>
<proper_name>Crash Instance</proper_name>
<type>INT</type>
</variable>
</variables>
</fact>
</facts>
Run Code Online (Sandbox Code Playgroud)
我想从节点中提取标签的所有内容,但仅限于崩溃事实。
到目前为止,这是我的代码。
def header(filename, fact):
lst = []
tree = ET.parse(filename) #read in the XML
for fact in tree.iter(tag = 'fact'):
factname = fact.find('name').text
if factname == fact: …Run Code Online (Sandbox Code Playgroud) 我有一个 GroupBy 对象,其行索引为整数。
light worst_injury count
1 5 10217
2 5 4067
3 5 2142
4 5 1690
5 5 25848
6 5 734
9 5 18
Run Code Online (Sandbox Code Playgroud)
我想重新命名行(而不是列!),以便“light”列包含特定字符串:
light worst_injury count
Day 5 10217
Dawn 5 4067
Dusk 5 2142
Dark- lit 5 1690
Dark- unlit 5 25848
Other 5 734
Unknown 5 18
Run Code Online (Sandbox Code Playgroud)
我有一个与每个数字 ['Day'、'Dawn' 等] 相对应的字符串列表,但我不知道如何在 GroupBy 函数调用之前或期间将它们设置为索引。我也尝试过制作数据透视表,但出于同样的原因似乎不可能这样做。
我想我可以编写一个脚本将原始数据更改为这些字符串,而不是数字。这似乎是一种效率较低的方法,但如果在事后或事前无法更改 groupby 对象,我愿意接受该选项。
这是现有的代码;它按光线和每个伤害级别对数据帧进行分组,然后进行计数:
df = pd.read_csv(filename, sep='|', usecols=['crash_deer_involv_assoc', 'worst_injury_in_accident', 'light', 'accident_month'])
for i in range(1,6):
inj = df[(df['worst_injury_in_accident'] == …Run Code Online (Sandbox Code Playgroud) 我有一个非常大的数据帧,我想从每列生成唯一的值.这只是一个样本 - 总共有20多列.
CRASH_DT CRASH_MO_NO CRASH_DAY_NO
1/1/2013 01 01
1/1/2013 01 01
1/5/2013 03 05
Run Code Online (Sandbox Code Playgroud)
我想要的输出是这样的:
<variable = "CRASH_DT">
<code>1/1/2013</code>
<count>2</count>
<code>1/5/2013</code>
<count>1</count>
</variable>
<variable = "CRASH_MO_NO">
<code>01</code>
<count>2</count>
<code>03</code>
<count>1</count>
</variable>
<variable = "CRASH_DAY_NO">
<code>01</code>
<count>2</count>
<code>05</code>
<count>1</count>
</variable>
Run Code Online (Sandbox Code Playgroud)
我一直在尝试使用.sum()或.unique()函数,正如我已经看过的关于这个主题的许多其他问题所建议的那样.
它们似乎都不适用于这个问题,并且所有人都说为了从每一列生成唯一值,您应该使用groupby函数,或者选择单个列.我有非常多的专栏(超过20个),因此仅仅通过写出df.unique ['col1','col2'...'col20'将它们组合在一起真的没有意义
我试过.unique(),. value_counts()和.count,但是我无法弄清楚如何应用任何这些来跨多个列工作,而不是groupby函数或上面链接中建议的任何内容.
我的问题是:如何从真正庞大的数据帧中的每个列生成唯一值的计数,最好是通过循环遍历列本身?(我很抱歉,如果这是重复的,我已经查看了很多关于这个主题的问题,虽然他们看起来也应该为我的问题工作,但我无法弄明白如何调整它们以使它们得到它们为我工作.)
到目前为止这是我的代码:
import pyodbc
import pandas.io.sql
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\<filename>.accdb')
sql_crash = "SELECT * FROM CRASH"
df_crash = pandas.io.sql.read_sql(sql_crash, conn)
df_c_head = df_crash.head()
df_c_desc = df_c_head.describe() …Run Code Online (Sandbox Code Playgroud) 我正在尝试根据几个条件过滤数据帧.然后,我想从一个单独的,更大的数据帧中删除该子集.
df = pd.DataFrame({ 'A' : ['UNKNOWN','UNK','TEST','TEST'],
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo' })
df2 = pd.DataFrame({ 'A' : ['UNKNOWN','UNK','TEST','TEST','UNKOWN','UNKKK'],
'E' : pd.Categorical(["test","train","test","train",'train','train']),
'D' : np.array([3] * 6,dtype='int32'),
'F' : 'foo' })
rgx = r'UNKNOWN|UNK'
df_drop = df.loc[df['A'].str.contains(rgx, na=False, flags=re.IGNORECASE, regex=True, case=False)]
df2 = df2[~df_drop]
Run Code Online (Sandbox Code Playgroud)
我想要df2的以下输出:
A D E F
2 TEST 3 test foo
3 TEST 3 train foo
Run Code Online (Sandbox Code Playgroud)
相反,我收到以下错误:
TypeError:一元〜:'str'的坏操作数类型
我没有直接过滤df2的原因是我想让df_drop成为自己独立的数据帧,以便保留我丢弃的记录.
我想我误解了一元是如何工作的.或者我犯了语法错误.但我找不到它,以前没有任何解决方案(例如,从数据帧中删除NaN)似乎适用于此处.