Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

python - Update columns in pandas Dataframe like excel

It's slightly embarassing to ask for an excel functionality in python but I need help finding an efficent way to do this so I can breakaway from excel in this project.

For me an advantage in excel is a table which the columns all update based on input in another columns. One way I imagined to do this is in functions:

def update_columns(x, y):
    mt = x * y
    sm = x + y
    sb = x - y
    dv = x / y
    cols = {'x' : x, 'y' : y, 'mt' : mt, 'sm' : sm, 'sb' : sb, 'dv' : dv}
    return cols

df = pd.DataFrame(columns=['x', 'y', 'mt', 'sm', 'sb', 'dv'])
new_vals = [(10, 5), (15, 3), (40, 4)]

for i in new_vals:
    x, y = i
    cols = update_columns(x, y)
    df = df.append(cols, ignore_index=True)

However, I imagine there being an eleganter, more pythonic way of going about this. Is it possible to use embedded lambda functions in a list or dict? Or some collection functions such as named tupels, or a data class / attr class? Could someone please suggest something?

question from:https://stackoverflow.com/questions/65886227/update-columns-in-pandas-dataframe-like-excel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way you define your update_columns function, you can (and should) just pass the whole column:

new_vals = np.array(new_vals)

df = pd.DataFrame(update_columns(new_vals[:,0], new_vals[:,1]))

Output:

    x  y   mt  sm  sb    dv
0  10  5   50  15   5   2.0
1  15  3   45  18  12   5.0
2  40  4  160  44  36  10.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...