我尝试更彻底地了解描述符和显式属性名称的查找顺序。
我阅读了描述符howto,其状态如下:
调用的细节取决于obj是对象还是类:
...
对于类,机制在type.__getattribute__
()中,它转换B.x
为B.__dict__['x'].__get__(None, B)
我在__class_
_ 上进行了测试,因为它是的数据描述符object
In [47]: object.__class__
Out[47]: type
Run Code Online (Sandbox Code Playgroud)
因此,type
由于type
class创建了包括object
class 在内的所有类,因此它按预期返回。根据“描述符howto”,object.__class__
将其转换为object.__dict__['__class__'].__get__(None, object)
。
但是,当我运行它时,输出是描述符本身,而不是描述符type
In [48]: object.__dict__['__class__'].__get__(None, object)
Out[48]: <attribute '__class__' of 'object' objects>
Run Code Online (Sandbox Code Playgroud)
我猜它返回描述符本身,因为在__get__
其中包含某种代码,例如:
if instance is None:
return self
Run Code Online (Sandbox Code Playgroud)
因此,我了解从类调用时返回描述符本身的原因。让我感到困惑的是不同的输出
当它说“ B.x
成B.__dict__['x'].__get__(None, B)
”时,我期望输出是相同的。他们为什么不同?
编辑:我在 @coldspeed、@wen-ben、@ALollz 指出的字符串中犯的菜鸟错误。np.nan
答案非常好,所以我不会删除这个问题来保留这些答案。
原文:
我已阅读此问题/答案groupby.first() 和 groupby.head(1) 之间有什么区别?
该答案解释说差异在于处理NaN
价值。然而,当我打电话groupby
给时as_index=False
,他们都选择了NaN
罚款。
此外,Pandas 具有groupby.nth
与 、head
和类似的功能first
groupby.first(), groupby.nth(0), groupby.head(1)
和 的区别是什么as_index=False
?
下面的例子:
In [448]: df
Out[448]:
A B
0 1 np.nan
1 1 4
2 1 14
3 2 8
4 2 19
5 2 12
In [449]: df.groupby('A', as_index=False).head(1)
Out[449]:
A B
0 1 np.nan
3 2 8
In [450]: df.groupby('A', as_index=False).first()
Out[450]:
A …
Run Code Online (Sandbox Code Playgroud) 我在python 3.7和pandas 0.24.2上
设定:
s = pd.Series(['10', '12', '15', '20', 'A', '31', 'C', 'D'])
In [36]: s
Out[36]:
0 10
1 12
2 15
3 20
4 A
5 31
6 C
7 D
dtype: object
Run Code Online (Sandbox Code Playgroud)
to_numeric与 errors='coerce'
pd.to_numeric(s, errors='coerce')
Out[37]:
0 10.0
1 12.0
2 15.0
3 20.0
4 NaN
5 31.0
6 NaN
7 NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)
to_numeric与errors=''
(空字符串)
pd.to_numeric(s, errors='')
Out[38]:
0 10.0
1 12.0
2 15.0
3 20.0
4 NaN
5 31.0
6 NaN
7 …
Run Code Online (Sandbox Code Playgroud) 我有一个 pandas df,其中每一行都是单词列表。该列表有重复的单词。我想删除重复的单词。
我尝试在 for 循环中使用 dict.fromkeys(listname) 来迭代 df 中的每一行。但这将单词分成字母表
filepath = "C:/abc5/Python/Clustering/output2.csv"
df = pd.read_csv(filepath,encoding='windows-1252')
df["newlist"] = df["text_lemmatized"]
for i in range(0,len(df)):
l = df["text_lemmatized"][i]
df["newlist"][i] = list(dict.fromkeys(l))
print(df)
Run Code Online (Sandbox Code Playgroud)
预期结果是==>
['clear', 'pending', 'order', 'pending', 'order'] ['clear', 'pending', 'order']
['pending', 'activation', 'clear', 'pending'] ['pending', 'activation', 'clear']
Run Code Online (Sandbox Code Playgroud)
实际结果是
['clear', 'pending', 'order', 'pending', 'order'] ... [[, ', c, l, e, a, r, ,, , p, n, d, i, g, o, ]]
['pending', 'activation', 'clear', 'pending', ... ... [[, ', p, e, n, …
Run Code Online (Sandbox Code Playgroud)