私信  •  关注

U10-Forward

U10-Forward 最近回复了
4 年前
回复了 U10-Forward 创建的主题 » Python如何将一个数据帧的两列组合成一个列表?

这不起作用,因为它不会按同一索引添加,请使用以下列表理解:

print([x for i in zip(df['data1'], df['data2']) for x in i])
4 年前
回复了 U10-Forward 创建的主题 » 从CSV读取数据并使用Python将其更改为tuple

不使用 tuple

with open('data.csv') as f:
    data = [line[0] for line in csv.reader(f)]
4 年前
回复了 U10-Forward 创建的主题 » 如何使用comprehension从python中的字典中创建值列表

使用此列表理解:

print([i[1] for i in yourdictionary.values()])

['Apple Inc', 'Alphabet Inc', 'Credit Suisse AG']

yourdictionary 以你字典的真实名字命名。

4 年前
回复了 U10-Forward 创建的主题 » Python比较两个数据帧的列并生成匹配行的索引

尝试使用:

color_df = expdf.loc[expdf['condition'].isin(faultdf.index), 'color']

你差点就搞定了, 'color'

编辑:

订购数据帧:

color_df = expdf[expdf['condition'].isin(faultdf.index)].set_index('condition').reindex(fault_df.index).reset_index()
4 年前
回复了 U10-Forward 创建的主题 » 在python中替换字典的值

使用字典理解 get :

d1_new = {k: d2.get(v, v) for k, v in d.items()}

{('a', 'b'): 300.0, ('b', 'c'): 0.21000000000000002, ('a', 'c'): 0.462, ('c', 'e'): 0.68, ('b', 'a'): 0.21000000000000002, ('c', 'd'): 4.2}
4 年前
回复了 U10-Forward 创建的主题 » Python-尝试控制输入时出错

因为您使用的是Python2,所以要么升级到Python3,要么替换:

player_one = input("Player One, make your move! ")

player_two = input("Player two, make your move! ")

使用:

player_one = raw_input("Player One, make your move! ")

player_two = raw_input("Player two, make your move! ")
4 年前
回复了 U10-Forward 创建的主题 » python中try语句的放置位置

这是因为如果不在try except部分中运行函数,它将始终运行,因为函数将始终在不被调用的情况下工作,如果在try except中调用它,它将工作:

try:
    def divide (n1, n2):
        d = n1/n2
    print(divide(0,0))
except :
    print("Wrong")

它将提供:

Wrong

但在所有的解决方案中,你的1个解决方案是最好的。

4 年前
回复了 U10-Forward 创建的主题 » python/pandas-从地址中删除街道号

试用使用 str.rstrip 以下内容:

df['street'] = df['street'].str.rstrip('\d+')
5 年前
回复了 U10-Forward 创建的主题 » 如何选择列表中的特定元素并使用它们(python)

IIUC:

>>> l=[]
>>> numbers=[1,2,3,4,5]
>>> l.append(numbers[1])
>>> l
[2]
>>> 

使用 append 以及索引。

然后, l 将具有一个值,该值是 numbers 是的。

4 年前
回复了 U10-Forward 创建的主题 » 奇数python列表

为什么不:

def odd(n):
    return list(range(1, n * 2, 2))
5 年前
回复了 U10-Forward 创建的主题 » python错误:“type”类型的“type error”参数不可iterable

变化 if rand not in list: lis.append(rand) if rand not in lis: lis.append(rand)

告诉你为什么?

  • 检查 in 关键字 list (这不是一个iterable对象)

  • 键入:-)

所以你一定想登记 lis 名单。

5 年前
回复了 U10-Forward 创建的主题 » 在python中如何将一个文本字符串拆分为两列

听起来像是 sentences 例如:

sentences=[['1','foobar'],['2','blahblah']]

然后尝试:

print('\n'.join(['\t'.join(i) for i in sentences]))
5 年前
回复了 U10-Forward 创建的主题 » 如何在pandas python中为字符串创建汇总列[duplicate]

或做 apply :

df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))

演示:

>>> df['col1']=df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> 
5 年前
回复了 U10-Forward 创建的主题 » 用python格式化html

您在错误的位置结束了字符串,因此请使用下面的完整代码:

titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
html_text = '''<html>
<head>
    <style type="text/css">
        table { border-collapse: collapse;}
        td { text-align: center; border: 5px solid #ff0000; border-style: dashed; font-size: 30px; }
    </style>
</head>
<body>
    <table width="100%" height="100%" border="5px">
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
    </table>
</body>
</html>''' % (titles[0], titles[1], titles[2], titles[3], titles[4])

f = open('temp.html', 'w')
f.write(html_text)
f.close()

所以现在您将得到预期的html文件。

5 年前
回复了 U10-Forward 创建的主题 » 在python中如何将一行中的数字读入变量和元组

很接近,就用 my_tuple 打开包装( * )一开始:

a, b, c, d, *my_tuple = map(int, line.split())

现在:

print(a,b,c,d,my_tuple,sep='\n')

输出:

6
10
11
2
[23, 37]
5 年前
回复了 U10-Forward 创建的主题 » 如何将字典列表转换为python panda数据帧?

把它转换成 DataFrame 像往常一样, pd.DataFrame(...) :

>>> lod=[{'ticker': 'KMG', 'cap_mm': 'NA', 'when': '--'}, {'ticker': 'SFIX', 'cap_mm': '2,665', 'when': 'amc'}]
>>> pd.DataFrame(lod)
  cap_mm ticker when
0     NA    KMG   --
1  2,665   SFIX  amc
>>>

所以在问之前记得试一下…

AS @CertainPerformance 说,用 re.M 结束时的标志 findall :

print(re.findall(my_regex,my_string,re.M))

演示:

>>> import re
>>> my_regex = r'^Credits$'
>>> my_string = "based upon extrinsic circumstances, as discussed in Serrano v. Priest, 20 Cal.3d 25, 49.\n\nCredits\n(Added by Stats.1977, c. 1197, p. 3979,  1. Amended by Stats.1993, c. 645 (S.B.764),  2.)"
>>> print(re.findall(my_regex,my_string,re.M))
['Credits']

或与一起使用 r'(?m)^Credits$' :

>>> import re
>>> my_regex = r'(?m)^Credits$'
>>> my_string = "based upon extrinsic circumstances, as discussed in Serrano v. Priest, 20 Cal.3d 25, 49.\n\nCredits\n(Added by Stats.1977, c. 1197, p. 3979,  1. Amended by Stats.1993, c. 645 (S.B.764),  2.)"
>>> print(re.findall(my_regex,my_string,re.M))
['Credits']
4 年前
回复了 U10-Forward 创建的主题 » python中的board[x,y]`和board[x][y]`有区别吗?

他们能做到这一点,因为他们使用的是numpy,这不会造成错误。

>>> a = np.array([[1,1,1], [1,2,2], [1,2,2]])
>>> a[1,1]
2
>>> # equivalent to
>>> a = [[1,1,1], [1,2,2], [1,2,2]]
>>> a[1][1]
2
>>> 
5 年前
回复了 U10-Forward 创建的主题 » python:根据另一个数据帧的日期范围更新列的值

解决方案1:

添加:

df['Event']=events['Event'].tolist()*2

到代码末尾。

那么现在:

print(df)

是:

        Date          Event        Place
0 2017-01-01    UniHolidays   university
1 2017-01-01  PublicHoliday  residential
2 2017-01-01  PublicHoliday     hospital
3 2017-01-02    UniHolidays   university
4 2017-01-02  PublicHoliday  residential
5 2017-01-02  PublicHoliday     hospital

————————————————————————————————————————————————————————————————————————————————————————————————————————————--

解决方案2:

如果希望他们添加到正确的位置,请执行以下操作:

df=df.drop('Event',1)
df.insert(2,'Event',events['Event'].tolist()*2)

在代码的末尾。

那么现在:

打印(df)

输出:

        Date        Place          Event
0 2017-01-01   university    UniHolidays
1 2017-01-01  residential  PublicHoliday
2 2017-01-01     hospital  PublicHoliday
3 2017-01-02   university    UniHolidays
4 2017-01-02  residential  PublicHoliday
5 2017-01-02     hospital  PublicHoliday

————————————————————————————————————————————————————————————————————————————————————————————————————————————————-

解决方案1 + 解决方案2 ,将起作用,

但最好还是做得与众不同。

更新:

用途:

df=df.drop('Event',1)
df.insert(2,'Event',events['Event'].tolist()*(len(df['Event'])/len(events['Event'].tolist())))

在代码的末尾。

那么现在:

打印(df)

输出:

日期地点事件
0 2017-01-01大学节假日
1 2017-01-01住宅公共假日
2 2017-01-01医院公共假日
3 2017-01-02大学假期
4 2017-01-02住宅公共假日
5 2017-01-02医院公共假日
5 年前
回复了 U10-Forward 创建的主题 » 如何读取此python代码?var1=var2=var3
var1 = var2 == var3

手段:

  1. 创建一个名为 var1

  2. 将它赋给真-假布尔值,即 var2 等于 var3 (使用 == 操作员)

下面是一个例子:

>>> var2=1
>>> var3=1
>>> var2==var3
True
>>> var1 = var2==var3
>>> var1
True
>>> 
5 年前
回复了 U10-Forward 创建的主题 » 我正在用python开发一些实践数据集[关闭]

这个 isnull 为每个值返回一个布尔语句,any转到每个列以检查是否有trues,然后进一步使用any,另一个any t将检查是否有trues

如果你不知道, 无空 检查每个值的numpy nan

另一方面 any 可以有一个 axis 参数,如果是1,则表示每行,否则不是。

示例(请阅读注释):

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'a':[np.nan,2,3], 'b':[2,np.nan,4]})
>>> df.isnull() # for each value
       a      b
0   True  False
1  False   True
2  False  False
>>> df.isnull().any() # for each column
a    True
b    True
dtype: bool
>>> df.isnull().any(axis=1) # for each row
0     True
1     True
2    False
dtype: bool
>>> df.isnull().any().any() # for any value 
True
5 年前
回复了 U10-Forward 创建的主题 » python,打印输入中出现最多的单词或字母[关闭]

你也可以 max 具有 key argument ,那么列表理解就需要计算所有这些,因为 最大值 只需要一个:

>>> words = ['green', 'green','green', 'yellow','orange','orange','orange']
>>> list(set([i for i in words if words.count(i) == words.count(max(words,key=words.count))]))
['green', 'orange']
>>> 
5 年前
回复了 U10-Forward 创建的主题 » 如何用清单理解实现python中的内置集

一种简单的分类方法 set 按元素的索引是列表 l :

def unique(l):
    return list(sorted(set(l),key=l.index))
print(unique([1,2,3,3]))

输出:

[1, 2, 3]